Finding a String Within Another String


To check whether a particular String a is being contained in a String b or not, we can use the method String.contains() with the following syntax:

b.contains(a); // Return true if a is contained in b, false otherwise

The String.contains() method can be used to verify if a CharSequence can be found in the String. The method looks for the String a in the String b in a case-sensitive way.

class Example
{
	public static void main (String[] args) throws java.lang.Exception
	{
		String text = "Programming is fun!";
		String word1 = "Programming";
		String word2 = "logic";
 
		System.out.println(text.contains(word1)); // prints true
		System.out.println(text.contains(word2)); // prints false
	}
}

To find the exact position where a String starts within another String, use String.indexOf():

class FindIndexes
{
	public static void main (String[] args) throws java.lang.Exception
	{
		String str = "Java is amazing!";
		int a = str.indexOf('a');          // the first 'a' in the string is at index 1
		int b = str.indexOf("is");         // the index of the first occurrence of "is" in str is 5
		int c = str.indexOf('z');          // c is -1 because 'z' was not found in the string
		int d = str.indexOf("amazing!");   // d is 8 because "amazing!" starts at index 8 in str
 
		System.out.println(a); // prints 1
		System.out.println(b); // prints 5
		System.out.println(c); // prints -1
		System.out.println(d); // prints 8
	}
}

The String.indexOf() method returns the first index of a char or String in another String. The method returns -1 if it is not found.

Note : The String.indexOf() method is case sensitive.

Example of search ignoring the case:

class IndexAndContains
{
	public static void main (String[] args) throws java.lang.Exception
	{
		String string1 = "Programming is fun!";
		String string2 = "gRa";
 
		System.out.println(string1.indexOf(string2));     // -1
		System.out.println(string1.toLowerCase().contains(string2.toLowerCase())); // true
		System.out.println(string1.toLowerCase().indexOf(string2.toLowerCase()));  // 7
	}
}

Basic Programs