Java String IndexOf Example

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.

  1. 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
  2. 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
  3. 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
  4. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!