java tutorial - Java Strings indexOf() method - java programming - learn java - java basics - java for beginners



Java strings indexof

Learn Java - Java tutorial - Java strings indexof - Java examples - Java programs

Description

Java Strings indexOf() method in Java has the following options:

  • public int indexOf (int ch) - Returns the index in the given line of the first occurrence of the specified character or -1 if the character does not occur.
  • public int indexOf (int ch, int fromIndex) - It returns a index in the given line of first occurrences of specified character then it starts a search at the specified index. -1 if this character does not occurs, returns -1.
  • int indexOf (String str) - Returns the index in the given line of the first occurrence of the specified substring. -1 if this substring does not occur, -1 is returned.
  • int indexOf (String str, int fromIndex) - Returns the index in the given line of the first occurrence of the specified substring starting at the specified index. If not, -1 is returned.

Syntax


public int indexOf (int ch)

or

public int indexOf (int ch, int fromIndex)

or

int indexOf (String str)

or

int indexOf (String str, int fromIndex)
click below button to copy the code. By - java tutorial - team

Options

Detailed information about the parameters:

  • ch is a character;
  • fromIndex - index to start the search (from);
  • str is a string.

Sample Code

import java.io. *;

public class Test {

   public static void main (String args []) {
      String Str = new String("Welcome to wikitechy.com");
      String SubStr1 = new String ("Prog");
      String SubStr2 = new String ("Srog");

      System.out.print("Found index:");
      System.out.println (Str.indexOf ('o'));
      System.out.print("Found index:");
      System.out.println(Str.indexOf ('o', 5));
      System.out.print("Found index:");
      System.out.println(Str.indexOf (SubStr1));
      System.out.print("Found index:");
      System.out.println(Str.indexOf (SubStr1, 21));
      System.out.print("Found index:");
      System.out.println(Str.indexOf (SubStr2));
   }
}
click below button to copy the code. By - java tutorial - team

Output

$javac Test.java
$java -Xmx128M -Xms16M Test
Found index:4
Found index:9
Found index:-1
Found index:-1
Found index:-1

Related Searches to Java Strings indexOf() method