Friday 10 August 2012

Searching a String for a Character or a Substring in Java


This example shows how we can search a word or a character within a Java String object using indexOf and lastIndexOf methods of the String class.

public class SearchStringExample {

 public static void main(String[] args) {

  // declare a String object
  String strOrig = "Hello world Hello World";

  /**
   * To search a particular word in a given string use,
   * int indexOf(String str) method. It returns the index
   * within this string of the first occurrence of the
   * specified substring if found. Otherwise it returns
   * -1.
   **/

  int intIndex = strOrig.indexOf("Hello");

  if (intIndex == -1) {
   System.out.println("Hello not found");
  } else {
   System.out.println("Found Hello at index " + intIndex);
  }

  /**
   * we can also search a word after particular position
   * using indexOf(String word, int position) method.
   **/

  int positionIndex = strOrig.indexOf("Hello", 11);
  System.out.println("Index of Hello after 11 is " + positionIndex);

  /**
   * Use lastIndexOf method to search a last occurrence
   * of a word within string.
   **/
  int lastIndex = strOrig.lastIndexOf("Hello");
  System.out.println("Last occurrence of Hello is at index " + lastIndex);

  /**
   * To search a particular character in a given string use,
   * int indexOf(int ch) method. It returns the index within
   * this string of the first occurrence of the specified
   * character if found.Otherwise it returns -1.
   **/
  int indexOf_e = strOrig.indexOf('e');

  if (indexOf_e == -1) {
   System.out.println("Character 'e' not found");
  } else {
   System.out.println("Found character 'e' at index " + indexOf_e);
  }

  /**
   * we can also search a character after particular position
   * using indexOf(int ch, int position) method.
   **/

  int positionIndex_e = strOrig.indexOf('e', 11);

  System.out.println("Index of character 'e' after 11 is "
    + positionIndex_e);

  /**
   * Use lastIndexOf method to search a last occurrence of
   * a character within string.
   **/
  int lastIndex_e = strOrig.lastIndexOf('e');

  System.out.println("Last occurrence of 'e' is at index " + lastIndex_e);

 }
}


The output is:


Found Hello at index 0
Index of Hello after 11 is 12
Last occurrence of Hello is at index 12
Found character 'e' at index 1
Index of character 'e' after 11 is 13
Last occurrence of 'e' is at index 13

No comments:

Post a Comment