Replace with empty string replaces newChar around all the characters in original string

前端 未结 4 1501
甜味超标
甜味超标 2021-01-20 07:13

I was just working on one of my java code in which I am using Java String.replace method. So while testing the replace method as in one situation I am planning to put junk v

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-20 07:46

    The native Java java.lang.String implementation (like Ruby and Python) considers empty string "" a valid character sequence while performing string operations. Therefore the "" character sequence is effectively everywhere between two chars including before and after the last character.

    It works coherently with all java.lang.String operations. See :

    String abc = "abc";
    System.out.println(abc.replace("", "a"));  // aaabaca instead of "abc"
    System.out.println(abc.indexOf("", "a"));  // 0 instead of -1
    System.out.println(abc.contains("", "a")); // true instead of false
    

    As a side note :

    This behavior might be misleading because many other languages / implementations do not behave like this. For instance, SQL (MySQL, MSSQL, Oracle and PostgreSQL) and PHP do not considers "" like a valid character sequence for string replacement. .NET goes further and throws System.ArgumentException: String cannot be of zero length. when calling, for instance, abc.Replace("", "a").

    Even the popular Apache Commons Lang Java library works differently :

    org.apache.commons.lang3.StringUtils.replace("abc", "", "a")); /* abc */
    

提交回复
热议问题