我想在字符串中每两个字符后添加空格。
例如:
javastring
我想把它变成:
ja va st ri ng
我怎样才能做到这一点?
答案 0 :(得分:25)
您可以使用正则表达式'..'
匹配每两个字符,并将其替换为"$0 "
以添加空格:
s = s.replaceAll("..", "$0 ");
您可能还想修剪结果以删除末尾的额外空格。
看到它在线工作:ideone。
或者你可以添加一个负前瞻断言,以避免在字符串末尾添加空格:
s = s.replaceAll("..(?!$)", "$0 ");
答案 1 :(得分:2)
//Where n = no of character after you want space
int n =2;
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - n;
while (idx > 0){
str.insert(idx, " ");
idx = idx - n;
}
return str.toString();
Explanation, this code will add space from right to left:
str = "ABCDEFGH" int idx = total length - 2; //8-2=6
while (8>0)
{
str.insert(idx, " "); //this will insert space at 6th position
idx = idx - n; // then decrement 6-2=4 and run loop again
}
The final output will be
AB CD EF GH
答案 2 :(得分:1)
我为此写了一个通用解决方案......
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
然后这样称呼它......
String result = InsertSpaces.insertCharacterForEveryNDistance(2, "javastring", ' ');
System.out.println(result);