java 在字符之间添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11149342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:58:38  来源:igfitidea点击:

Adding space between characters

javastringspace

提问by Babu R

I want to add space after every two chars in a string.

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

For example:

例如:

javastring 

I want to turn this into:

我想把它变成:

ja va st ri ng

How can I achieve this?

我怎样才能做到这一点?

回答by Mark Byers

You can use the regular expression '..'to match each two characters and replace it with "$0 "to add the space:

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

s = s.replaceAll("..", "
s = s.replaceAll("..(?!$)", "
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();
");
");

You may also want to trim the result to remove the extra space at the end.

您可能还想修剪结果以删除末尾的额外空间。

See it working online: ideone.

看看它在线工作:ideone

Alternatively you can add a negative lookahead assertion to avoid adding the space at the end of the string:

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

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
} 

回答by Nitin Divate

//Where n = no of character after you want space

//Where n = no of character after you want space

AB CD EF GH

Explanation, this code will add space from right to left:

说明,这段代码会从右到左添加空格:

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

The final output will be

最终输出将是

String result = InsertSpaces.insertCharacterForEveryNDistance(2, "javastring", ' ');
System.out.println(result);

回答by Arif Nadeem

I wrote a generic solution for this...

我为此写了一个通用的解决方案......

##代码##

Then call it like this...

那就这样叫吧……

##代码##