20

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?

roottraveller
  • 7,942
  • 7
  • 60
  • 65
george_h
  • 1,562
  • 2
  • 19
  • 37
  • How would you prove there is not an empty string at the start of fileName? You would have to find a character that appears in the empty string but does not appear in fileName. – Patricia Shanahan Aug 23 '13 at 09:22
  • Ï think, at least thats why I'm here, a contains search on "" should throw exception because its illogical. I'm sure from some c basic 30 years ago attitude, this is complient with old compilers.. But its not logical for a _normal_ person. – Christian Dec 06 '19 at 09:35

2 Answers2

41

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • @george_h More like uselessly formal at the beginning :D – nanofarad Aug 23 '13 at 09:29
  • If it needs an explanation its not logical. This is just one of those things that just are the way they are. If strings _always contains empty_ the search is pointless and developer should be made aware. – Christian Dec 06 '19 at 09:37
  • 2
    @Christian if strings did not contain empty substrings, then the definition of contains would be badly inconsistent with mathematical theory, which is arguably worse. – nanofarad Dec 06 '19 at 13:19
11

"" occurs between every character and also at start and end.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Xabster
  • 3,710
  • 15
  • 21