string.replace(ch,'')和string.replace(""+ch,"")有什么区别

class pola {
    public static void main(String[] args) {
        String name = "fast and furious";
        char s = 'f';
        System.out.println(name.replace(s, ''));    //---->line 1
        System.out.println(name.replace("" + s, "")); //---->line 2
    }
}

line1和 和有2什么不一样?

回答

第一行调用replace(char, char) ,第二行调用replace(CharSequence, CharSequence)

这两种方法之间的一个很大区别是,第一种方法只能对char值进行 1 对 1 的替换(即,一个字符的每次出现都被另一个字符完全替换),而第二种方法可以替换任意长的字符串与另一个任意长的字符串。

在你的情况下:

  • 第一个调用f用一个 nul-character替换每个,有效地用一个不可打印的字符替换它们中的每一个。
  • 第二个调用用"f"0-character替换每个 1-character 字符串"",有效地删除所有f字符。
  • @i_am_ssr notice: don't expect this to behave like it would in C (i.e., adding a `''` in the middle of a string would effectively truncate it). Java strings don't work like that, if that was your doubt.
  • To see that there is a difference: compare the lengths of the resulting strings.

以上是string.replace(ch,'')和string.replace(""+ch,"")有什么区别的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>