Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does contains() method find empty string in non-empty string in Java

Tags:

java

string

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?

like image 364
george_h Avatar asked Aug 23 '13 09:08

george_h


People also ask

Does string contain empty string?

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.

Does every string contain empty string Java?

An empty string occurs in every string.

How do you check a string is empty or not in Java?

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.

Does the empty language contain the empty string?

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.


2 Answers

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.

like image 176
nanofarad Avatar answered Oct 04 '22 11:10

nanofarad


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

like image 10
Xabster Avatar answered Oct 04 '22 10:10

Xabster