2 回答

TA貢獻1827條經(jīng)驗 獲得超9個贊
您可以使用 :
String str = "Abcd123";
if (str.replaceAll("\\D", "").length() > 0) { // check if the string contain numbers
str = str.replaceFirst("\\d", " $0"); // if yes put a space before the first degit
}
輸出
Abcd 123

TA貢獻1797條經(jīng)驗 獲得超4個贊
你可以使用這個簡單的邏輯:
String str = "Abcd123";
String newStr = "";
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))){
newStr = newStr + " " + str.substring(i);
break;
} else {
newStr = newStr + str.charAt(i);
}
}
System.out.println(newStr);
在這里,我們遍歷字符串中的每個字符,并在找到第一個數(shù)字后立即中斷循環(huán)。
輸出 :
第 123 章
添加回答
舉報