2:23 am - Tuesday March 28, 2017

Retrieve index position of a char from specified index int indexOf(int ch, int fromIndex)

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

                         This method returns the index value for the specified character in a given string. It is used for the first occurrence of the specified character.If the string value has some same character in thesequence of characters then indexOf() is used for displaying the first occurrence of the character and LastIndexOf() is used for displaying the last occurrence of the given character.

Example Program

 public class Index {

 public static void main(String[] args)

 {

    String s="I LIKE CHOCOLATE";

    int i=s.indexOf('O');

    int j=s.lastIndexOf('O');

    System.out.println("The Index value for the first occurrence for

    character:" +i);

    System.out.println("The Index value for the Last occurrence for

    character:" +j);

  }

 }

Output

       The Index value for the first occurrence for character:9

       The Index value for the Last occurrence for character:11

Description

                           In the above program, string value is assigned for the s variable. Here the integer variable i is used to find the index for the first occurrence of the character ‘O’.The same ‘O’ is specified in two places in that string. To find the index of last occurrence value lastIndexof() is used.

Filed in: Java Examples

Comments are closed.