Saturday, 11 August 2012

Determining If a String Contains a Substring in Java


To check if a string contains a substring, I usually use:

if(s.indexOf(sub) >= 0)

For JDK 5 or later, a contains method can also be used, which seems to be a little more readable:

if(s.contains(sub))

The signature of contains method is:

public boolean contains(java.lang.CharSequence s);

Note that CharSequence is a super-interface of String, StringBuffer, StringBuilder, java.nio.CharBuffer, javax.swing.text.Segment. So you can pass any of the 5 types to contains method.

The current implementation of contains method just convert the param to String and calls indexOf.

See the example given below:


public class SearchSubStringExample {

 public static void main(String args[]) {

  String str = "Hello World";

  int index = str.indexOf("World");

  if (index >= 0) {
   System.out.println("Substring 'World' found at index:" + index);
  }

  if (str.contains("World")) {

   System.out.println("Substring 'World' found.");
  }

 }
}


The output is:


Substring 'World' found at index:6
Substring 'World' found.

No comments:

Post a Comment