如何在Java中现有字符串的每个字符后插入空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4469984/
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
How to insert Space after every Character of an existing String in Java?
提问by notme
I need to insert a space after every character of a string.
我需要在字符串的每个字符后插入一个空格。
i.e.
String name = "Joe";
IE
String name = "Joe";
should become: "J o e"
应该变成: "J o e"
采纳答案by Peter Kofler
Shorter would be using a regex:
更短的是使用正则表达式:
System.out.println("Joe".replaceAll(".(?!$)", "String joe = "Joe";
StringBuilder sb = new StringBuilder();
for (char c: joe.toCharArray()) {
sb.append(c).append(" ");
}
System.out.println(sb.toString().trim());
"));
回答by Andre Brito
Something like:
就像是:
char[] stringArray = strOrig.toCharArray();
StringBuilder sb = new StringBuilder();
for(int index=0; index < stringArray.length; index++) {
sb.append(stringArray[index]);
sb.append(" ");
}
回答by thotheolh
You can convert Joe to char[] by using String's toCharArray() then traverse char[] to grab the char into another char[] and as you add the char to the second char[], you add a space character '" "'. Set a if-else within the loop to detect the last character so that you wouldn't add a space character by accident behind the last character. Use a String to valueOf() the resulting char[] to turn it into a String object.
您可以使用 String 的 toCharArray() 将 Joe 转换为 char[],然后遍历 char[] 以将 char 抓取到另一个 char[] 中,当您将 char 添加到第二个 char[] 时,添加一个空格字符 '" "' . 在循环中设置一个 if-else 来检测最后一个字符,这样您就不会在最后一个字符后面意外添加空格字符。使用 String 到 valueOf() 结果 char[] 将其转换为 String 对象。
回答by davek
"Joe Black".replaceAll("\B", " ") -> "J o e B l a c k"
回答by rodion
This will space out all letters in each word and not between words
这将隔开每个单词中的所有字母,而不是单词之间
"Joe Black".replaceAll("\B|\b", " ") -> " J o e B l a c k "
This will put space for each character (including original spaces)
这将为每个字符放置空间(包括原始空间)
String joe = "Joe";
StringBuilder sb = new StringBuilder();
String sep = "";
for (char c: joe.toCharArray()) {
sb.append(sep).append(c);
sep = " ";
}
System.out.println(sb.toString());
回答by Eric
Removing the final space:
删除最后的空间:
val stringWithSpaceAfterEvery4Chars = stringWith16Chars?.replace("....".toRegex(), "stringWith16Chars = "123456789012"
")
回答by Kishan Solanki
For Android & Kotlinusers, if you want to add space after every Xcharacters then use this
对于Android 和 Kotlin用户,如果您想在每X 个字符后添加空格,请使用此
stringWithSpaceAfterEvery4Chars = "1234 5678 9012"
Here I added 4 dots in methodto add space after every 4th characterin my whole string. If you want space after every 2 characters then add only 2 dotsin the method.
在这里,我在方法中添加了4 个点,以在整个字符串中的每 4 个字符后添加空格。如果您希望每 2 个字符后有空格,则只在方法中添加 2 个点。
My variables:
我的变量:
##代码##and the output would be,
输出将是,
##代码##