Example of indexOf method of string class in java.

Example of indexOf method of string class in java.


Posted in : Core Java Posted on : November 9, 2010 at 4:35 PM Comments : [ 0 ]

In this section, you will see the example of indexOf method of string class in java.

Example of indexOf method of string class in java.

In this example, you will see how to access the index value of particular character or string. The IndexOf is a method of string class. It returns index of particular string or character. Different forms of indexOf(...) method...

1- indexOf(int ch) -- It returns the index of first occurrence of the specified character in the given string.
2- indexOf(int ch, int fromIndex) -- It returns the index of first occurrence of the specified character in the given string. Search starts from specified index.
3- indexOf(String str) --
It returns the index of first occurrence of the specified string in the given string.
4- indexOf(String str, int fromIndex) --It returns the index of first occurrence of the specified string in the given string. Search starts from specified index.

 Code:
IndexOfMethod.java
public class IndexOfMethod {
  public void useIndexOfMethod() {
	String str = "This is bharat singh";
	char c = 'i';
	System.out.println("String  : " + str);
	String searchString = "is";
	// Display the index of given character
	System.out.println("First occurrence of character " + c + " : "
			+ (str.indexOf(c)));
	// Display the first occurrence of a character from specified index
	System.out.println("First occurrence of character " + c
			+ " search start at specified index  4 = "
			+ (str.indexOf(c, 4)));
	// Display the first occurrence of a string
	System.out.println("First Index of string " + searchString + " : "
			+ (str.indexOf(searchString)));
	// Display the first occurrence of a string from specified index
	System.out.println("First occurrence of string : " + searchString
			+ " : search start at specified index  3 = "
			+ (str.indexOf(c, 3)));
	     }
     public static void main(String[] args) {
	IndexOfMethod obIndexOfMethod = new IndexOfMethod();
	obIndexOfMethod.useIndexOfMethod();
     }
  }
Output:
String : This is bharat singh
First occurrence of character i : 2
First occurrence of character i search start at specified index 4 = 5
First Index of string is : 2
First occurrence of string : is : search start at specified index 3 = 5

Download this code.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics