Java 如何从字符串中删除所有空格?
我有一个包含0,1的字符串,不幸的是还有很多空格。我想写一个方法,它将去掉所有的空格,并返回只有1和0的字符串 我该怎么做Java 如何从字符串中删除所有空格?,java,Java,我有一个包含0,1的字符串,不幸的是还有很多空格。我想写一个方法,它将去掉所有的空格,并返回只有1和0的字符串 我该怎么做 String example= new String("1 011 01 1"); String shouldReturnStringWithoutWhiteSpaces(String given){ String cleanString //some action which will "transform "1 011 01 1" into "
String example= new String("1 011 01 1");
String shouldReturnStringWithoutWhiteSpaces(String given){
String cleanString
//some action which will "transform "1 011 01 1" into "1011011"
return cleanString;
}
你能行
String cleanString = given.replaceAll("\\s", "");
这将用零替换所有空白。主要的技巧是\\s
,它在运行时变成\s
,这意味着所有的空格。您可以这样做
String cleanString = given.replaceAll("\\s", "");
这将用零替换所有空白。主要技巧是
\\s
在运行时变为\s
,这意味着所有空格。使用带默认分隔符的字符串上的扫描仪。将找到的任何内容添加到新字符串中
string result = "";
Scanner scan = new Scanner(example);
while(scan.hasNext())
result += scan.next();
在带有默认分隔符的字符串上使用Scanner
。将找到的任何内容添加到新字符串中
string result = "";
Scanner scan = new Scanner(example);
while(scan.hasNext())
result += scan.next();
String something=given.replaceAll(“+”,”)String something=given.replaceAll(“+”,”)你可以这样做
String res = given.replace(" ", "");
或
第一个是replace(CharSequence目标,CharSequence replacement;)
第二个是replaceAll(stringregex,stringreplacement)代码>
有关CharSequence和String之间差异的更多信息,请参见。如果您想让函数String应该返回stringwithout-whitespaces(字符串给定)
返回字符串,您应该使用第二个;) 你可以这样做
String res = given.replace(" ", "");
或
第一个是replace(CharSequence目标,CharSequence replacement;)
第二个是replaceAll(stringregex,stringreplacement)代码>
有关CharSequence和String之间差异的更多信息,请参见。如果您想让函数String应该返回stringwithout-whitespaces(字符串给定)
返回字符串,您应该使用第二个;) 是的。报告如下duplicate@Leonardo-完成了,完成了。还是很绿,所以我都没想过。没问题!生活和学习是的,是的。报告如下duplicate@Leonardo-完成了,完成了。还是很绿,所以我都没想过。没问题!生活和学习哈为什么投票失败?不知道正则表达式是如何工作的?为什么要否决?不确定正则表达式是如何工作的?