Java String Find matching characters indexOf(), lastIndexOf()

February 21, 2011 | String and StringBuffer
To Java String find matching, we use three methods - overloaded indexOf() and lastIndexOf() and charAt(). Index numbers are given by the JVM implicitly to the characters in the string; the first character is given 0, the second one as 1 and so on. These index numbers are helpful in programming in searching operations.

Following are the details of the overloaded Java String Find methods.

  1. int indexOf(int ch): Returns an integer value of the index number of the first occurrence of the character, ch, passed as parameter, in the given string. The comparison starts from left to right. If matching is not found, returns -1.
  2. int indexOf(String str): Returns an integer value of the index number of the first occurrence of the string str passed as parameter, in the given string. If matching is not found, returns -1.
  3. int lastIndexOf(int ch): Returns an integer value of the index number of the last occurrence of the character, ch, passed as parameter, in the given string. Remember, the comparison starts from right to left. If matching is not found, returns -1.
  4. int lastIndexOf(String str): Returns the index number of the last occurrence of the string str passed as parameter, in the given string. If matching is not found, returns -1.
  5. char charAt(int indexNumber): Returns the character existing at the specified index, indexNumber, passed as parameter, in the given string. If the specified index number does not exist in the string, the method throws an unchecked exception, StringIndexOutOfBoundsException.

With the above methods, we can find out at what index number the specified character or string exist in the given string, and in contrary, to find out the index number of a character present in a string. Following program deals with the above methods.

public class Matching
{
  public static void main(String args[])
  {
    String str = "pqrpqrpqr";

    System.out.println(str.indexOf('r'));       // prints 2
    System.out.println(str.indexOf("qrp"));   	// prints 1
    System.out.println(str.indexOf('u'));       // prints -1

    System.out.println(str.lastIndexOf('p')); 	// prints 6
         
    System.out.println(str.charAt(3));          // prints p

    System.out.println(str.length());           // 9, total characters 
    System.out.println(str.charAt(12));         // throws StringIndexOutOfBoundsException
  }
}

Java String Find

Following are the Java String Find methods used in the above program.

indexOf('r') returns the index number of the first occurrence of the character r passed as parameter, in the given string str. Infact, there are three r characters, but it returns that of the first r. The checking starts from left to right and once a suitable match occurs, further checking is discontinued and the matching index number is returned.

indexOf('u') returns -1 as the character u does not exist in the string str. Similarly, lastIndexOf('p') returns the last occurrence of p in the string str. The checking starts now from right to left.

The length() returns the number of characters existing in the string. charAt(12) returns an exception, StringIndexOutOfBoundsException, as the specified index number, 12, does not exist in the string.

Java String find Matching the Start and End

Here, we use two methods - overloaded startsWith() and endsWith(). These methods check whether a string starts and ends with a specified string passed as parameter, in the given string.

Following are the details of the methods.

  1. boolean startsWith(String str): Returns true if the string str exist at the starting of the given string, else false.
  2. boolean startsWith(String str, int indexNum): Returns true if the string str exist at the starting of the index indexNum in the given string, else false.
  3. boolean endsWith(String str): Returns true if the string str exist at the ending of the given string, else false.

The above methods are useful to separate strings that meets a specified constraint like to separate all the Web addresses that ends with com.

public class StartingOrEnding
{
  public static void main(String args[])
  {
     String s1 = "Sure Nag Rao";

     System.out.println(s1.startsWith("Sure"));        // true	
     System.out.println(s1.startsWith("Nag", 5));      // true
     System.out.println(s1.endsWith("Rao"));           // true

     System.out.println(s1.startsWith("God"));         // false
     System.out.println(s1.endsWith("Almighty"));      // false

                    // one live demo of separating all the names of the students ending with Rao

     String students[] = { "Sure Nag Rao",  "Sridhar",  "Jyostna", "Srinivas Rao" };
     System.out.println("\nFollowing are the students that ends with Rao");

     for(int i = 0; i < students.length; i++)
     {
        if(students[i].endsWith("Rao"))
        {
            System.out.println(students[i]);
        }
      }
  }
}

[caption id="attachment_520" align="aligncenter" width="578" caption="Output screen of StartingOrEnding.java"]Java String Find[/caption]

Following is the method description of methods used in the program.

  1. s1.startsWith("Sure") returns true as the specified string Sure exists in the given string s1.
  2. s1.startsWith("Nag", 5) returns true as the string Nag exists at the specified index number 5 in the given string s1.
  3. s1.endsWith("Rao") returns true as the given string s1 ends with Rao.
  4. s1.startsWith("God") returns false as the given string s1 does not start with God.
  5. s1.endsWith("Almighty") returns false as the string s1 does not end with Almighty.