Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从字符串中删除所有空格?_Java - Fatal编程技术网

Java 如何从字符串中删除所有空格?

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 "

我有一个包含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 "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-完成了,完成了。还是很绿,所以我都没想过。没问题!生活和学习哈为什么投票失败?不知道正则表达式是如何工作的?为什么要否决?不确定正则表达式是如何工作的?