Signup/Sign In

How to Find a word or substring in String

In this post, we are finding a word or substring in the String. The String is a sequence of characters and a class in Java.

To find a word in the string, we are using indexOf() and contains() methods of String class.

The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.

The contains() method is used to check whether a string contains the specified string or not. It returns a boolean value either true or false. If the specified string is found then it returns true, false otherwise.

Time for an Example:

Let's create an example to find a word in the string. Here, we are using indexOf() method that returns an index of the specified substring. See the example below.

public class Main {
	public static void main(String[] args){
		String str = "This sentance contains find me string";
		System.out.println(str);
		// find word in String
		String find = "find me";
		int i = str.indexOf(find);
		if(i>0)
			System.out.println(str.substring(i, i+find.length()));
		else 
			System.out.println("string not found");
	}
}


This sentance contains find me string
find me

Example 2

Let's create another example to find a word in the string. Here, we are using the contains() method that returns true, if the specified string is found. See the example below.

public class Main {
	public static void main(String[] args){
		String str = "This sentance contains find me string";
		System.out.println(str);
		// find word in String
		String find = "find me";
		boolean val = str.contains(find);
		if(val)
			System.out.println("String found: "+find);
		else 
			System.out.println("string not found");
	}
}


This sentance contains find me string
String found: find me



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.