Java.lang.String.indexOf() Method

Advertisements


Description

The java.lang.String.indexOf(int ch, int fromIndex) method returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
If a character with value ch occurs in the character sequence represented by this String object at an index no smaller than fromIndex, then the index of the first such occurrence is returned.

Declaration

Following is the declaration for java.lang.String.indexOf() method

public int indexOf(int ch, int fromIndex)

Parameters

  • ch-- This is a character (Unicode code point).

  • fromIndex-- This is the index to start the search from.

Return Value

This method returns the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

Exception

  • NA

Example

The following example shows the usage of java.lang.String.indexOf() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
 
    String str = "This is tutorialspoint";

    // returns positive value as character is located
    System.out.println("index of letter 't' =  "
    + str.indexOf('t', 14)); 
      
    // returns positive value as character is located
    System.out.println("index of letter 's' =  "
    + str.indexOf('s', 10)); 
      
    // returns -1 as character is not in the string
    System.out.println("index of letter 'e' =  "
    + str.indexOf('e', 5));
  }
}

Let us compile and run the above program, this will produce the following result:

index of letter 't' = 21
index of letter 's' = 16
index of letter 'e' = -1



Advertisements
Advertisements