Java 如何不使用“删除字符串中的间距”\\s";在爪哇?

Java 如何不使用“删除字符串中的间距”\\s";在爪哇?,java,removing-whitespace,Java,Removing Whitespace,我知道如何使用.replaceAll(“\\s+”,”)删除空格。但我需要的是这样的东西: for(i=0;i<string.length();i++) { if(ch==32) { //remove the character; } } for(i=0;iString str=“a b c d e”; 字符串newStr=“”; 对于(int i=0;i

我知道如何使用
.replaceAll(“\\s+”,”)删除空格。但我需要的是这样的东西:

for(i=0;i<string.length();i++) {
   if(ch==32) {
     //remove the character;
   }
}
for(i=0;i
String str=“a b c d e”;
字符串newStr=“”;
对于(int i=0;i

它将打印
abcde

您的问题仅包含要求-它不会显示您方面为自己解决此问题所做的任何努力。请将您的尝试添加到此问题中-因为此网站不是免费的“我们做您的(家庭)工作”服务。除此之外:请转到以了解如何/问什么。谢谢我已经思考了一段时间这个问题,这是我能想到的最远的问题。循环中的
String+=String
(或
String+=char
)是个坏主意(性能差)。如果你要为他们编写代码,至少要教给他们正确的方法,即使用
StringBuilder
。正如@Andreas所说,字符串连接是一个坏习惯,因为它每次都会生成一个新字符串。因此
StringBuilder
List
(使用
String.join
)使用起来很好。但我认为短代码更具可读性。还要注意,它只处理空格字符,而
\\s
相当于
[\t\n\x0B\f\r]
-它处理空格、换行符等。
String str = "a b c d e";
String newStr = "";
for (int i=0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch != 32)
        newStr += ch;
}
System.out.println(newStr);