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
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 */