java - 如何仅反转字符串中的数字
问题描述
输入: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
解决方案
此任务可以在没有正则表达式的情况下实现,将输入字符串拆分为子字符串等,仅借助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
推荐阅读
- r - R 中是否有代码可以根据其他标准区分同一列中的两个类别之间的差异?
- python - 创建一个程序,根据特定日期的温度计算分配给家庭供暖和制冷的天数
- c++ - 在 C++ 中测试多线程的最简单方法是什么?
- entity-framework-core - 配置 EF Core CLI 参数
- reactjs - react-papaparse 是否支持接受/拒绝文件类型
- r - tidymodels 不尊重固定的 set_engine 参数
- r - CTL - 中心极限定理,如何在 R 中使用它?
- amazon-web-services - 从 AWS Lambda 运行 sqlldr 或 sqlplus
- exception - 如何从 webflux 应用程序返回具有错误请求状态的异常消息
- package - 还原期间锁定依赖项生成的 nuget packages.lock.json 文件的架构