[英]Replace extra spaces in string with a single space in Java, without regex
[英]String replace() returns extra space in Java
考虑:
System.out.println(new String(new char[10]).replace("\0", "hello"));
有输出:
hellohellohellohellohellohellohellohellohellohello
但:
System.out.println(new String(new char[10]).replace("", "hello"));
有输出:
hello hello hello hello hello hello hello hello hello hello
这些额外空间来自哪里?
它不是一个空间。 这是你的IDE /控制台显示 \\0
字符默认情况下填充new char[10]
方式。
你没有用任何东西替换\\0
,所以它保持在字符串中。 而使用.replace("", "hello")
则只替换空字符串""
。 重要的是Java假定""
存在于:
因为我们可以得到"abc"
:
"abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
//^ ^ ^ ^
现在.replace("", "hello")
替换每个的那些""
与"hello"
,所以对于长度10的字符串,将放置其他11 hello
S(不是10),而无需修改\\0
,这将在以下示出你的输出像空格。
也许这会更容易掌握:
System.out.println("aaa".replace("", "X"));
|
代表每个""
。 我们将得到"|a|a|a|"
(注意有4 |
) ""
用X
将导致"XaXaXaX"
(但你的情况,而不是a
控制台将打印\\0
使用字符将看起来像空间) \\0
表示字符NUL
,它不等于空字符串""
。
当您尝试使用空char[10]
创建String
时,:
String input = new String(new char[10]);
此String
将包含10个NUL
字符:
|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|
当你调用input.replace("\\0", "hello")
, NUL
值( \\0
)将被hello
替换:
|hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|
当您调用input.replace("", "hello")
, NUL
值将不会被替换,因为它与空字符串""
不匹配:
|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|
您正在使用String#replace(CharSequence target, CharSequence replacement)
( 文档 )方法。
如果使用空目标字符序列replace("", replacement)
,则不会替换源中的元素,而是在每个字符之前插入 替换 。
这是因为""
匹配字符之间的位置,而不是字符本身。 因此,它们之间的每个位置都将被替换,即插入替换 。
例:
"abc".replace("", "d") // Results in "dadbdcd"
你的字符串在每个位置只包含char
的默认值,它是
\0\0\0\0\0\0\0\0\0\0
使用该方法因此导致:
hello\0hello\0hello\0hello\0hello\0hello\0hello\0hello\0hello\0hello\0
您的控制台可能会将字符\\0
显示为空格 ,而实际上它不是空格而是\\0
。
如果我在不同的控制台中试用你的代码,我得到:
确认字符确实不是空格而是不同的字符(即\\0
)。
char
的默认值是\
,也可以表示为\\0
。 所以你的new char[10]
包含10 \\0
s。
在第一个语句中,您明确地将\\0
替换为"hello"
。 但在第二个声明中,您省略了默认值。 您的IDE输出选择显示为空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.