Java.lang.String.indexOf() Method



Description

The java.lang.String.indexOf(String str) method returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that: this.startsWith(str, k) is true.

Declaration

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

public int indexOf(String str)

Parameters

str − This is value of a string.

Return Value

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

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 str1 = "Collections of tutorials at tutorials point";
     
      // returns index of first character of the substring "tutorials" 
      System.out.println("index =  " + str1.indexOf("tutorials")); 
      
      // returns -1 as substring "admin" is not located
      System.out.println("index =  " + str1.indexOf("admin"));    
   }
}

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

index = 15
index = -1
java_lang_string.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy