tags:

views:

460

answers:

3
String s1 = "The quick brown fox jumps over the lazy dog";
String s2 = "";
boolean b = s1.contains(s2);
System.out.println(b);

I run the Java code above, the b return true. Since s2 is empty, why does s1 contains s2?

I check the Java API, it write:

Returns true if and only if this string contains the specified sequence of char values.

Parameters: s - the sequence to search for Returns: true if this string contains s, false otherwise

+4  A: 

Similarly:

"".contains("");     // Returns true.

Therefore, it appears that an empty string is contained in any String.

coobird
+8  A: 

Empty is a subset of any string.

Think of them as what is between every two characters.

Kind of the way there are an infinite number of points on any sized line...

(Hmm... I wonder what I would get if I used calculus to concatenate an infinite number of empty strings)

Note that "".equals("") only though.

Bill K
Not really infinite - probably number of characters + 1, as there is an empty string before every character, and another at the end.
belugabob
You don't think there might be a "" between the "" and a letter? :)
Bill K
Just read your answer again, and realised that the 'line' you were talking about was a line drawn on a piece of paper. There could actually be a meta "" between each "" ;-)
belugabob
+2  A: 

no real explanation is given by Java (in either JavaDoc or much coveted code comments), but looking at the code, it seems that this is magic:

calling stack:

String.indexOf(char[], int, int, char[], int, int, int) line: 1591  
String.indexOf(String, int) line: 1564  
String.indexOf(String) line: 1546   
String.contains(CharSequence) line: 1934

code:

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
                   char[] target, int targetOffset, int targetCount,
                   int fromIndex) {
  if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
  }
      if (fromIndex < 0) {
        fromIndex = 0;
      }
  if (targetCount == 0) {//my comment: this is where it returns, the size of the 
    return fromIndex;    // incoming string is 0,  which is passed in as targetCount
  }                      // fromIndex is 0 as well, as the search starts from the 
                         // start of the source string
    ...//the rest of the method
akf