This is a weird behavior I found with Java's String.indexOf()
and String.contains()
methods. If I have a non-empty string says blablabla
and I try to look for an empty string inside it, it always returns true
whereas I would expect it to return false
.
So basically, why does the code below return true and 0 ?
String testThis = "";
String fileName = "blablablabla";
System.out.println(fileName.contains(testThis));
System.out.println(fileName.indexOf(testThis));
Logically (at least to me) ""
does not occur in blablablabla
but indexOf("")
says it does, why?
Using the isEmpty() MethodThe isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.
An empty string occurs in every string.
Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.
In formal treatments, the empty string is denoted with ε or sometimes Λ or λ. The empty string should not be confused with the empty language ∅, which is a formal language (i.e. a set of strings) that contains no strings, not even the empty string. The empty string has several properties: |ε| = 0.
An empty string occurs in every string. Specifically, a contiguous subset of the string must match the empty string. Any empty subset is contiguous and any string has an empty string as such a subset.
Returns true if and only if this string contains the specified sequence of char values.
An empty set of char values exists in any string, at the beginning, end, and between characters. Out of anything, you can extract nothing. From a physical piece of string/yarn I can say that a zero-length portion exists within it.
If contains returns true there is a possible substring(
invocation to get the string to find. "aaa".substring(1,1)
should return ""
, but don't quote me on that as I don't have an IDE at the moment.
""
occurs between every character and also at start and end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With