How do I determine if a String contains another String?
Author: Deron Eriksson
Description: This Java example shows how to determine if a String contains another String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

The StringContainsStringTest class demonstrates three different techniques that can be used to determine if a String exists in another String. The first technique is to use a String's contains() method. The second technique is to use a String's indexOf() method to look for a String's position in another String. If the String can't be found, indexOf() returns -1. The third technique is to use the contains() method of the StringUtils class of Commons LangS.

package test;

import org.apache.commons.lang.StringUtils;

public class StringContainsStringTest {

	public static void main(String[] args) throws Exception {

		String str = "This is the string to search";

		System.out.println("String to search: " + str);

		System.out.println("\nUsing String.contains():");
		System.out.println("str.contains(\"the\"): " + str.contains("the"));
		System.out.println("str.contains(\"The\"): " + str.contains("The"));

		System.out.println("\nUsing String.indexOf() processing:");
		System.out.println("(str.indexOf(\"the\") > -1 ? true : false): " + (str.indexOf("the") > -1 ? true : false));
		System.out.println("(str.indexOf(\"The\") > -1 ? true : false): " + (str.indexOf("The") > -1 ? true : false));

		System.out.println("\nUsing StringUtils.contains():");
		System.out.println("StringUtils.contains(str, \"the\"): " + StringUtils.contains(str, "the"));
		System.out.println("StringUtils.contains(str, \"The\"): " + StringUtils.contains(str, "The"));



The console output of StringContainsStringTest is shown below.

String to search: This is the string to search

Using String.contains():
str.contains("the"): true
str.contains("The"): false

Using String.indexOf() processing:
(str.indexOf("the") > -1 ? true : false): true
(str.indexOf("The") > -1 ? true : false): false

Using StringUtils.contains():
StringUtils.contains(str, "the"): true
StringUtils.contains(str, "The"): false