[英]adding space in between every word in java
I have a string that could look like this where there could be one or more spaces in between the words and this is just a sample of it我有一个看起来像这样的字符串,其中单词之间可能有一个或多个空格,这只是其中的一个示例
JAVA CODE STYLING AND RESOURCES
How can I insert/append white spaces in between every word using java to achieve this result如何使用 java 在每个单词之间插入/附加空格以实现此结果
JAVA CODE STYLING AND RESOURCES
from the above u can see that additional white spaces was added because there is a space already after the words except the last.从上面你可以看到添加了额外的空格,因为除了最后一个单词之外已经有一个空格。
On my own, I have attempted and all I could arrive is adding spaces after every character instead of words having one or more white spaces就我自己而言,我已经尝试过,我所能达到的只是在每个字符之后添加空格,而不是包含一个或多个空格的单词
Strictly speaking, if you really only want to add a space to a space which already exists in between words, you can match on the following regex pattern:严格来说,如果您真的只想在单词之间已经存在的空格中添加空格,则可以匹配以下正则表达式模式:
(?<=\w)([ ]+)(?=\w)
And then replace with the captured spaces along with one additional space.然后用捕获的空间和一个额外的空间替换。 Here is a sample script:
这是一个示例脚本:
String input = "JAVA CODE STYLING AND RESOURCES";
String output = input.replaceAll("(?<=\\w)([ ]+)(?=\\w)", "$1 ");
System.out.println(input); // JAVA CODE STYLING AND RESOURCES
System.out.println(output); // JAVA CODE STYLING AND RESOURCES
You can use replace()
method:您可以使用
replace()
方法:
String s1 = "JAVA CODE STYLING AND RESOURCES";
String s2 = s1.replace(" ", " "); //replaces all occurrences of " " to " "
// s2 is now: "JAVA CODE STYLING AND RESOURCES"
Answer from @Bug is probably the best, I can offer the most simple one: @Bug 的回答可能是最好的,我可以提供最简单的一个:
String string = "JAVA CODE STYLING AND RESOURCES";
String[] words = string.split(" ");
for (int i = 0; i < words.length-1; i++) {
words[i] = words[i]+" ";
}
I would suggest to do it like this.我建议这样做。
public class ReplaceExample1{
public static void main(String[] args){
String s1 = "JAVA CODE STYLING AND RESOURCES";
String replaceString = s1.replace(" ", " ");//replaces all occurrences of ' ' to ' '
System.out.println(replaceString);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.