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:-
/**Output of the program:-
* @(#) IndexOfString.java
* IndexOfString class demonstrates the working of indexOf() method of String class of lang package
* @version 15-May-2008
* @author Rose India Team
*/
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"));
}
}
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