繁体   English   中英

String replace()在Java中返回额外的空间

[英]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 ,它不等于空字符串""

长版

  1. 当您尝试使用空char[10]创建String时,:

     String input = new String(new char[10]); 

    String将包含10个NUL字符:

     |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL| 
  2. 当你调用input.replace("\\0", "hello")NUL值( \\0 )将被hello替换:

     |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello| 
  3. 当您调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM