Java-Get Position

Get Position

The indexOf( ) method provides the position of a specific character in the given string. For example, in the following program, the indexOf( ) method will return ‘2‘ as the answer. This method has returned the position of first occurrence of the specified character.

There is one more method known as the lastIndexOf( ) method. As the name suggests, this method will return the position of last occurrence of the specified character. For example, in the following program, as the character ‘c’ occurs last at the position ‘6’ in the string “abcdabcd”, the lastIndexOf( ) method will return the value ‘6’.

Program

final2

Program Source

public class Javaapp {
    
    public static void main(String[] args){
        
        String str1 = new String("abcdabcd");
        System.out.println("indexOf('c')     = "+str1.indexOf('c'));
        System.out.println("lastIndexOf('c') = "+str1.lastIndexOf('c'));
   }
}

Leave a Comment