Java.lang.StringBuilder.indexOf() Method

Advertisements


Description

The java.lang.StringBuilder.indexOf(String str) method returns the index within this string of the first occurrence of the specified substring.

Declaration

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

public int indexOf(String str)

Parameters

  • str -- This is the substring value.

Return Value

This method returns the index of the first character of the first such substring, if the string argument occurs as a substring within this object.If it does not occur as a substring, -1 is returned. .

Exception

  • NullPointerException -- if str is null.

Example

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

package com.tutorialspoint;

import java.lang.*;

public class StringBuilderDemo {

  public static void main(String[] args) {
  
    StringBuilder str = new StringBuilder("programming language");
    System.out.println("string = " + str);
  
    // returns the index of the specified substring
    System.out.println("Index of substring  = " + str.indexOf("age"));
    
    // returns -1 as substring is not found 
    System.out.println("Index of substring  = " + str.indexOf("k"));
  }
}  

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

string = programming language
Index of substring = 17
Index of substring = -1



Advertisements
Advertisements