3

So I'm an IB student and I'm taking Comp. Sci. we need to create a code to solve a problem, as i was writing my Java code I found the String.replaceAll(); that is helpful in writing my code. I had to remove any white spaces, and any new lines, so I found \\s+ and \\n. So as I enter the code String.replaceAll("\\s+",""); it didn't work, same with String.replaceAll("\\n","");. I have tried removing the " " but BlueJ, sends an error saying that \ is an illegal character. I checked if maybe the String.replaceAll(); doesn't works but it does work, so I came to a conclusion that something is wrong with \\s+ and \\n.

I have found an alternative in removing white spaces String.replaceAll(" ","");, but I still need a way to remove new lines.

Here is a part of the code

String name = InputString("Enter name: ");
String name1 = name.replaceAll("\\s+","");
   output(name1); // the output function is located in the IBIO which is provided because I'm and IB student

Alright so someone had given me a code that will remove all of the new lines \\n, but if people can give me the reason why my \\s+ not working that would be helpful.

4

4 回答 4

4

“它不起作用”是什么意思?

人们经常忘记的一件事是类String是不可变的。这意味着如果您调用类似replace()on a的方法String,则原始字符串不会更改;相反,该方法返回一个新字符串。

String s = "Hello World";

// Does not change the original string!
s.replaceAll("\\s+", ""); 

// Use this instead to assign s to the new string
s = s.replaceAll("\\s+", "");
于 2012-11-06T09:50:53.237 回答
3

真正难倒人们为什么\\s不起作用的一个可能原因是是否存在字符代码 0xa0(不间断空格)而不是正常空格。该方法replaceAll不会使用\\s正则表达式捕获 0xa0。相反,您必须执行以下操作:

String name1 = name.replaceAll("\\u00a0",""); 

替换不间断的空格。

于 2014-04-08T13:55:10.083 回答
0

这条线

System.out.println("Multiline \r\n String".replaceAll("\\s+", ""));

印刷

MultilineString

因此,我建议您发布您遇到问题的确切字符串文字,并生成确切的输出。

于 2012-11-06T09:51:41.493 回答
0

从字符串中删除换行符

String s = "Enter name :\n Your name ";
        s = s.replaceAll("\n", "");
于 2012-11-06T10:19:35.187 回答