在字符之间添加空格

问题描述 投票:6回答:3

我想在字符串中每两个字符后添加空格。

例如:

javastring 

我想把它变成:

ja va st ri ng

我该如何实现?

java string space
3个回答
30
投票

您可以使用正则表达式'..'来匹配每两个字符,并将其替换为"$0 "以添加空格:

s = s.replaceAll("..", "$0 ");

您可能还希望修剪结果以删除最后的多余空间。

[在线查看它的工作:ideone

或者,您可以添加否定的超前断言,以避免在字符串末尾添加空格:

s = s.replaceAll("..(?!$)", "$0 ");

3
投票

//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();

说明,此代码将从右至左添加空格:

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
} 

最终输出将是

AB CD EF GH

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);
© www.soinside.com 2019 - 2024. All rights reserved.