Java String search

Introduction

The String class has two methods to search a string for a specified character or substring:

indexOf()       Searches for the first occurrence of a character or substring. 
lastIndexOf()   Searches for the last occurrence of a character or substring. 

These two methods are overloaded in several different ways.

In all cases, the methods return the index at which the character or substring was found, or -1 if not found.

To search for the first occurrence of a character, use

int indexOf(int ch) 

To search for the last occurrence of a character, use

int lastIndexOf(int ch) 

To search for the first or last occurrence of a substring, use

int indexOf(String str)  
int lastIndexOf(String str) 

You can specify a starting point for the search using these forms:

int indexOf(int ch, int startIndex)       
int lastIndexOf(int ch, int startIndex)  
int indexOf(String str, int startIndex)  
int lastIndexOf(String str, int startIndex) 
// Demonstrate indexOf() and lastIndexOf().
public class Main {
  public static void main(String args[]) {
    String s = "the testing code from demo2s.com the site";

    System.out.println(s);/*from  w  w w.  j  av  a 2  s .c  o  m*/
    System.out.println("indexOf(t) = " +
                       s.indexOf('t'));
    System.out.println("lastIndexOf(t) = " +
                       s.lastIndexOf('t'));
    System.out.println("indexOf(the) = " +
                       s.indexOf("the"));
    System.out.println("lastIndexOf(the) = " +
                       s.lastIndexOf("the"));
    System.out.println("indexOf(t, 10) = " +
                       s.indexOf('t', 10));
    System.out.println("lastIndexOf(t, 60) = " +
                       s.lastIndexOf('t', 60));
    System.out.println("indexOf(the, 10) = " +
                       s.indexOf("the", 10));
    System.out.println("lastIndexOf(the, 60) = " +
                       s.lastIndexOf("the", 60));
  }
}



PreviousNext

Related