Searching Strings

Searching Strings

You can search a string for the occurrence of a character or another string.

Method Purpose
indexOf(int) Searches for the first occurrence of the specified character. Returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
indexOf(int ch, int fromIndex) Searches for the first occurrence of the specified character following the given offset.
indexOf(String) Searches for the first occurrence of the specified string.
indexOf(String, int) Searches for the first occurrence of the specified string following the given offset.
lastIndexOf(int) Searches backwards for the last occurrence of the specified character. Returns -1 if the character does not occur
lastIndexOf(int, int) Searches backwards for the last occurrence of the specified character preceding the given offset.
lastIndexOf(String) Searches backwards for the last occurrence of the specified string.
lastIndexOf(String, int) Searches backwards for the last occurrence of the specified string preceding the given offset.

Code

public class SearchingStrings {
	public static void main(String[] args) {
		String str = new String("Wish You Were Here");
		//indexOf()
		System.out.println("indexOf()");
		int index1 = str.indexOf('Y'); //5
		//case sensitive
		int index2 = str.indexOf('W',5); //9
		
		System.out.println(index1);
		System.out.println(index2);
		System.out.println(str.indexOf('w',5)); //-1
		System.out.println(str.indexOf("er")); //10
		System.out.println(str.indexOf("er",11)); //15
		
		//lastIndex()
		System.out.println("lastIndexOf()");
		int lastIndex1 = str.lastIndexOf('e'); //17
		//case sensitive
		int lastIndex2 = str.lastIndexOf('e',13); //12
		
		System.out.println(lastIndex1);
		System.out.println(lastIndex2);
		System.out.println(str.lastIndexOf('E')); //-1
		System.out.println(str.lastIndexOf("er")); //15
		System.out.println(str.lastIndexOf("er",12)); //10
	}
}

indexOf()
5
9
-1
10
15
lastIndexOf()
17
12
-1
15
10

Leave a Comment