Home » Core Java » lang » String » Search String with indexOf method

About 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.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments