String

Search String with indexOf method

This is an example of how to search a String using the indexOf method of String class. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Searching a String implies that you should:

  • Create a new String.
  • Use indexOf(String str) API method of String. This method returns the index within this string of the first occurrence of the specified substring.
  • Use indexOf(String str, int fromIndex) API method of String. This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
  • Use lastIndexOf(String str) API method of String. This method returns the index within this string of the last occurrence of the specified substring.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

public class SearchStringWithIndexOfMethod {
	
	public static void main(String[] args) {
		
		String s = "Hello Java Code Geeks";
		 
		int index = s.indexOf("Hello");
		 
		if (index == -1) {
			System.out.println("'Hello' not found");
		}
		else {
			System.out.println("Found 'Hello' at " + index);
		}
		 
		index = s.indexOf("a", 8);
		System.out.println("Index of 'a' after index 8 is " + index);
		
		int lastIndex = s.lastIndexOf("e");
		System.out.println("Last occurrence of 'e' is at index " + lastIndex);
		
	}

}

Output:

Found 'Hello' at 0
Index of 'a' after index 8 is 9
Last occurrence of 'e' is at index 18

 
This was an example of how to search a String using the indexOf method of String in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button