首页 > 解决方案 > 如何仅反转字符串中的数字

问题描述

输入:123ABC458 输出:321ABC854

public static void main(String []args){
    String str="123ABC564";
    int count=0;
    int ans=0;
    int firstindex=0;
    char[] ch = str.toCharArray();
    for(int i=0;i<ch.length;i++){
        if(Character.isDigit(ch[i])){
            if(ans==0){
                firstindex=i;

            }
            count++;
        }
        else{
            int lastindex=count+firstindex-1;
            while(firstindex<lastindex){
                char temp=ch[firstindex];
                ch[firstindex]=ch[lastindex];
                ch[lastindex]=temp;
                firstindex++;
                lastindex--;
            }
            ans=0;
            count=0;
            firstindex=0;
        }
    }
    for (char c : ch){
        System.out.print(c);
    }
}

}

谁能告诉我这段代码有什么问题我使用这段代码得到的输出是 12BA3C564

标签: javastringnumbers

解决方案


此任务可以在没有正则表达式的情况下实现,将输入字符串拆分为子字符串等,仅借助StringBuilder::insert(int offset, char c)StringBuilder::append(char c)使用简单的索引计算insert

public static String revertDigits(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    StringBuilder sb = new StringBuilder(str.length());
    
    for (int i = 0, j = 0, n = str.length(); i < n; i++) {
        char c = str.charAt(i);
        if (Character.isDigit(c)) {
            sb.insert(j, c); // append in "reverse" mode
        } else {
            sb.append(c);
            j = i + 1;  // store the last position of a non-digit
        }
    }
    
    return sb.toString();
}

测试:

String str="123ABC564";

System.out.println(str + '\n' + revertDigits(str));

输出

123ABC564
321ABC465

推荐阅读