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

Ans*_*nsh 17 java string replace char

考虑:

System.out.println(new String(new char[10]).replace("\0", "hello"));
Run Code Online (Sandbox Code Playgroud)

有输出:

hellohellohellohellohellohellohellohellohellohello 
Run Code Online (Sandbox Code Playgroud)

但:

System.out.println(new String(new char[10]).replace("", "hello")); 
Run Code Online (Sandbox Code Playgroud)

有输出:

hello hello hello hello hello hello hello hello hello hello
Run Code Online (Sandbox Code Playgroud)

这些额外空间来自哪里?

Psh*_*emo 15

它不是一个空间.这是您的IDE /控制台显示 默认情况下填充的\0字符的方式new char[10].

你没有替换\0任何东西,所以它保持在字符串中.相反,.replace("", "hello")你只是替换空字符串"".重要的是Java假定""存在于:

  • 字符串的开头,
  • 字符串结束,
  • 以及每个角色之间

因为我们可以得到"abc":

"abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
      //^          ^          ^          ^
Run Code Online (Sandbox Code Playgroud)

现在.replace("", "hello")来替换每一个的那些"""hello",所以对于长度10的字符串时,它将会把额外11 hello秒(不10),而无需修改\0,这将在示出在你的输出像的空间.


也许这会更容易掌握:

System.out.println("aaa".replace("", "X"));
Run Code Online (Sandbox Code Playgroud)
  • 让我们""用as 表示|.我们会得到"|a|a|a|"(注意有4个|)
  • 所以更换""X会导致"XaXaXaX"(但你的情况,而不是a您的控制台将打印\0使用字符将看起来像空间)


孙兴斌*_*孙兴斌 12

精简版

\0表示字符NUL,它不等于空字符串"".

长版

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

    String input = new String(new char[10]);
    
    Run Code Online (Sandbox Code Playgroud)

    String将包含10个NUL字符:

    |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|
    
    Run Code Online (Sandbox Code Playgroud)
  2. 当你打电话时input.replace("\0", "hello"),NULvalue(\0)将被替换为hello:

    |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|
    
    Run Code Online (Sandbox Code Playgroud)
  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|
    
    Run Code Online (Sandbox Code Playgroud)


Zab*_*uza 8

说明

您正在使用该方法String#replace(CharSequence target, CharSequence replacement)(文档).

如果用一个空的目标字符序列调用replace("", replacement)它会不会取代源中的元素,但插入更换每一个字符之前.

这是因为""匹配字符之间的位置,而不是字符本身.因此,它们之间的每个位置都将被替换,即插入替换.

例:

"abc".replace("", "d") // Results in "dadbdcd"
Run Code Online (Sandbox Code Playgroud)

您的字符串仅包含char每个位置的默认值,它是

\0\0\0\0\0\0\0\0\0\0
Run Code Online (Sandbox Code Playgroud)

使用该方法因此导致:

hello\0hello\0hello\0hello\0hello\0hello\0hello\0hello\0hello\0hello\0
Run Code Online (Sandbox Code Playgroud)

显示

你大概控制台显示的字符\0空白,而它实际上不是一个空白,但\0.

如果我在不同的控制台中试用你的代码,我得到:

在此输入图像描述

确认角色确实不是空格而是不同的(即\0).