开发者社区> 问答> 正文

如何将带有数字和字母的字符串分隔为仅数字?

public static String carRentalCode(String licensePlate) {
    // precondition:    licensePlate is a valid plate as described in pdf
    // postcondition:   return the car rental code for the licensePlate as described
    int values = 0;
    int ascii = 0;
    int sum = 0;
    int convert = 0;
    int count = 0;
    int a = 0;
    char letter;
    String license;
    char[] ch = new char[licensePlate.length()];
    for (int i = 0; i < licensePlate.length(); i++) { 
        ch[i] = licensePlate.charAt(i); 
    }
    for(int i = 0; i< ch.length; i++)
    {
        if(Character.isDigit(ch[i]))
        {
            values += Character.getNumericValue(ch[i]);
        }
        if(Character.isAlphabetic(ch[i]))
        {
            ascii += (int) ch[i];
            count++;
        }
    }
    sum = values + ascii;
    convert = sum%26 + 65;
    letter = (char)convert;
    String[] letters = licensePlate.split("\\d+");
    String lowercase = Arrays.toString(letters).toLowerCase();
    String code = Integer.toString(sum);
    return letter + code + lowercase;

在这里,我应该根据给定的车牌(测试仪车牌为"123ABC456")返回租车代码。我剩下的唯一问题是我的小写字母返回,[[,abc]]而不是正确的答案[abc]。

您如何固定前面的空白区域,并且有两对而不是一对?还是有其他方法仅获取字符串中(ABC)与数字(123和456)分开的字母并返回它?

预期:```js L219[abc]


实际:  ```js
L219[[, abc]]

展开
收起
垚tutu 2019-12-04 16:40:57 1092 0
1 条回答
写回答
取消 提交回答
  • #include

    我更改了一些代码,用于String.toCharArray()创建字符数组,而不是逐字符地将其复制,然后将所有数字替换为空字符串以仅获取字母字符

    public static String carRentalCode(String licensePlate) {
        // precondition:    licensePlate is a valid plate as described in pdf
        // postcondition:   return the car rental code for the licensePlate as described
        int values = 0;
        int ascii = 0;
        int sum = 0;
        int convert = 0;
        char letter;
    
        char[] ch = licensePlate.toCharArray();
    
        for (int i = 0; i < ch.length; i++) {
            if (Character.isDigit(ch[i])) {
                values += Character.getNumericValue(ch[i]);
            }
            if (Character.isAlphabetic(ch[i])) {
                ascii += ch[i];
            }
        }
        sum = values + ascii;
        convert = sum % 26 + 65;
        letter = (char) convert;
    
        String lowercase = licensePlate.replaceAll("\\d+", "").trim().toLowerCase();
        String code = Integer.toString(sum);
        return letter + code + "[" + lowercase + "]";
       }
    
    2019-12-04 16:41:29
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载