我需要创建一个方法,输入将是字符串,例如:asd321tre2。 输出应为:eas321dtr2。字符应向前移动一个位置,但数字应保持在同一位置。 输入:字符串s1 =" abc23sd23&#34 ;; 输出:字符串s2 =" dab23cs23&#34 ;;
public static String revertTheString (String s) {
String helper = s.replaceAll("\\d", "");
helper = helper.substring(helper.length()-1) + helper.substring(0, helper.length()-1);
int start = 0, end = 0;
StringBuilder revert = new StringBuilder(s);
for (int i = 0; i< s.length(); i++) {
if(Character.isDigit(s.charAt(i))){
end = i;
revert = revert.replace(start, end, helper.substring(start, end));
while(Character.isDigit(s.charAt(i))){
i++;
start = i;
}
}
}
return revert.toString();
}
答案 0 :(得分:1)
你可以尝试交换第一个和最后一个char值,如下所示。
===========================================
String s = "asd321tre2";
char[] charr = s.toCharArray();
int end = 0;
for (int i = s.length(); i <= 0; i--) {
if (Character.isLetter(charr[i])) {
end = i;
}
}
String output = charReplace(end, charr);
}
private static String charReplace(int end, char[] ch) {
for (int i = 0; i < ch.length; i++) {
if (Character.isLetter(ch[i])) {
char tmp = ch[i];
ch[i] = ch[end];
ch[end] = tmp;
}
}
String output = String.valueOf(ch);
return output;
}
===========================================
希望这有帮助。
谢谢, Parthiban