Monday, 7 May 2012

Java String indexOf Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Java String indexOf Example

String class indexOf method example

String class indexOf method example:- This example demonstrates the working of indexOf method. this method returns the index location of character specified.

Syntax:-indexOf('h') 


Here is the code:-

  /**
  * @(#) IndexOfString.java
  * IndexOfString class demonstrates the working of indexOf() method of String class of lang package
  * 
  */  


public class IndexOfString {
  public static void main(String args[]){
    
    // Method here returns index location or number position of the specified character.         
    String str = "hare krishna hare krishna krishna krishna hare hare";
    int prabhu = str.indexOf('h'), heram;
    
    System.out.println("Index of 'h' in String 'str' is: " + prabhu);    
    System.out.println("Index of 'k' in String 'str' is: " + str.indexOf("k"));
        
    //For a word or sequence of charaters, method returns the index location of letter with which the word starts.
    System.out.println("Index of 'krishna' in String 'str' is: " + str.indexOf("krishna"));
      
  }
}
Output of the program:-
-----------------------
Index of 'h' in String 'str' is: 0
Index of 'k' in String 'str' is: 5
Index of 'krishna' in String 'str' is: 5

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...