Java String class consist of methods for finding the index of occurrence in the given string literals. If there is no occurrence of the given characters, then it will return the “-1”. The following are the few methods which is very useful to find the string values.
- indexOf(char) – Returns the index of the character first occurrence in the given string. If it does not occur as a substring, -1 is returned
- lastIndexOf(char) – Returns the index of the character last occurrence in the given string. If it does not occur as a substring, -1 is returned
- lastIndexOf(string) – Returns the index within this string of the last occurrence of the specified substring. If it does not occur as a substring, -1 is returned
- lastIndexOf(string,fromIndex) – Returns the index within this string of the last occurrence of the specified substring. If it does not occur as a substring, -1 is returned
Look at the below example for String indexOf() methods.
StringIndexExample.java
package javabeat.net.core; /** * String indexOf() Example * @author krishna * */ public class StringIndexExample { public static void main(String args[]) { String str = "Java Strings"; // indexOf(char) System.out.println("indexOf(char) : " + str.indexOf('a')); // indexOf(char) - non exist character System.out.println("indexOf(char) - non exist character : " + str.indexOf('z')); // lastIndexOf(char) System.out.println("lastIndexOf(char) : " + str.lastIndexOf('a')); // lastIndexOf(string) System.out.println("lastIndexOf(string) : " + str.lastIndexOf("Str")); // lastIndexOf(string,fromIndex) System.out.println("lastIndexOf(string,fromIndex) : " + str.lastIndexOf("Str", 4)); } }
Output…
indexOf(char) : 1 indexOf(char) - non exist character : -1 lastIndexOf(char) : 3 lastIndexOf(string) : 5 lastIndexOf(string,fromIndex) : -1