gpt4 book ai didi

java - 如何仅反转字符串中的数字

转载 作者:行者123 更新时间:2023-12-04 13:06:14 25 4
gpt4 key购买 nike

输入: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

最佳答案

您可以使用 Java regex APIStringBuilder 轻松解决它。正则表达式 \d+ 指定一位或多位数字。使用 Java 正则表达式 API,您可以找到数字、它们的开始位置和结束位置,您可以使用它们来构建所需的字符串。

演示:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
public static void main(String[] args) {
// Tests
String[] samples = { "123ABC458", "123ABC458XYZ", "123ABC458XYZ367", "ABC123XYZ", "ABC123XYZ" };
for (String s : samples)
System.out.println(numbersInverted(s));

}

static String numbersInverted(String str) {
StringBuilder sb = new StringBuilder();
Matcher matcher = Pattern.compile("\\d+").matcher(str);
int lastInitialPos = 0;
while (matcher.find()) {
int start = matcher.start();
String inverted = new StringBuilder(matcher.group()).reverse().toString();
sb.append(str.substring(lastInitialPos, start)).append(inverted);
lastInitialPos = matcher.end();
}
if (sb.length() == 0) // If no number was found
return str;
else
return sb.append(str.substring(lastInitialPos)).toString();
}
}

输出:

321ABC854
321ABC854XYZ
321ABC854XYZ763
ABC321XYZ
ABC321XYZ

ONLINE DEMO

关于java - 如何仅反转字符串中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69324518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com