java 在java中将带有空格的字符数组转换为字符串时如何删除该字符串中的空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15943053/
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
In java when converting a char array with spaces to a String how to remove the spaces in that String?
提问by sdfasdfw
String output = new String(encryptText);
output = output.replaceAll("\s", "");
return output;
replaceAll("\\s", "");
doesn't work
replaceAll("\\s", "");
不起作用
回答by Petar Ivanov
String output = new String(encryptText);
output = output.replaceAll(" ", "");
return output;
回答by Aakash Mangal
I was facing the same problem then I searched a lot and found that, it is not a space character but a null value which is transformed into string from character array. This resolved the issue for me -
我遇到了同样的问题,然后我搜索了很多,发现它不是空格字符而是一个空值,它从字符数组转换为字符串。这为我解决了问题-
output.replaceAll(String.valueOf((char) 0), "");
回答by CloudyMarble
Your code works fine for me, see here
你的代码对我来说很好用,请看这里
Anyway you can use the StringUtils.trimAllWhitespacefrom the spring framework:
反正你可以使用StringUtils.trimAllWhitespace从Spring框架:
output = StringUtils.trimAllWhitespace(output);
回答by Marco Forberg
You could use the non-regex-version replace to do the job:
您可以使用非正则表达式版本替换来完成这项工作:
output = output.replace(" ", "");
回答by Deepak Bala
Use String.replaceAll(" ","")
or if you want to do it yourself without a lib call, use this.
使用String.replaceAll(" ","")
或者如果您想在没有 lib 调用的情况下自己完成,请使用它。
String encryptedString = "The quick brown fox ";
char[] charArray = encryptedString.toCharArray();
char [] copy = new char[charArray.length];
int counter = 0;
for (char c : charArray)
{
if(c != ' ')
{
copy[counter] = c;
counter++;
}
}
char[] result = Arrays.copyOf(copy, counter);
System.out.println(new String(result));