Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java String Searching

Introduced in 1.5 version.
When working with strings, you often need to search within a given string. There are several overloaded versions of the method indexOf() available in the String class for searching a string forward, the lastIndexOf() method for searching a string backward, and the regionMatches() method for comparing a region of text within a string. We"ll discuss each of these methods in turn.

The IndexOf() Method:

How do you search for a particular character within a string and, if it occurs, at what position? For example, which index position does the character J occupy in the string "OCPJP"? The following program contains the code that uses the indexOf() method to answer this question.

public class SearchString1 {
	public static void main(String[] s) {
		String str = "Swati Sucharita";
		System.out.println("Character J occurs at index: " + str.indexOf('i'));

Output: Character J occurs at index 4

Quite easy, right? The indexOf() method searches the specified character here it is, the character and returns the first occurrence of the character (note that the index starts from 0, not 1!). Now, let's search a substring within in a given string. The indexOf() method is overloaded, and one definition of the method takes a string as a search argument. Listing 7-2 shows an example.

// Demonstrates searching a substring within a string using indexOf() method
public class SearchString2 {
	public static void main(String[] s) {
		String str = "I am preparing for BPUT semester exam";
		System.out.println("Substring \"for\" occurs at index: " + str.indexOf("for"));

Substring "for" occurs at index: 15

(Please note that we used the escape character, \, to print for within double quotes.). What will happen if the search string does not exist in the string? For instance, if you search "fort instead of for in above example, you"ll get this result:

Substring "for" occurs at index: -1
Well, a failed indexOf search results in the value 1, indicating "not found".
These two were simple problems; now let try a slightly harder one. Given a big string, how can you find how many times a given string (say am) occurs within that string? Not to worry in this case there is another version of the indexOf() method.

In this method you can specify an index from which the search should commence. The following program shows the implementation.

// This example demonstrates how to search multiple occurences of a search string
public class SearchString3 {
	public static void main(String args[]) {
		String s = "I am a student. I am preparing for my semester exam";
		int index = 0;
		while (s.indexOf("am", index) > â ˆ ’ 1) {
			index = s.indexOf("am", index);
			System.out.println("Substring \"am\" occurs at index: " + index);

Output Substring "am" occurs at index: 2
Substring "am" occurs at index: 18

It uses a while loop to check whether more occurrences of the search string exist in the input string. It also maintains an index from which you search ahead. It increments the index variable after each occurrence of the search string so that the next occurrence of the search string can be found. If you want to search the last occurrence of the search string, you can use the overloaded versions of the lastIndexOf() method defined in the String class.

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc