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.