Wednesday, 24 April 2013

indexOf , lastIndexOf in java

String class provides two methods that allow you to search a string for a specified character or substring:-

1. IndexOf() is a method of the String class. Since the indexOf method is overloaded, I will be using the indexOf(String str) version in this example. According to the Documentation this method "Returns the index within this string of the first occurrence of the specified string." So, if you wanted to find the position of '<' in the String 'Arun <ar>Kumar' and print it out "first occurence of < 4 index".


2. lastIndexOf() Searches for the last occurrence of a character or substring.This method "Returns the index within this string of the last occurrence of the specified string." So, if you wanted to find the position of '>' in the String 'Arun<ar>Kumar' and print it out "last Occurence of >7".

Sample Code :-

public class StringPattern {

  String userName = "ArunKumar";
  int firstIndex = userName.indexOf("<", 0); // 0 is starting index
  int lastIndex = userName.lastIndexOf(">");

  String htmlTag = userName.substring(firstIndex, lastIndex).concat(">");

  System.out.println(" first occurence of < " + userName.indexOf("<")
    + "\t last Occurence of  >" + userName.lastIndexOf(">") + "\t"
    + htmlTag + " tag substring");

while running this sample code print :-
first occurence of < 4 last Occurence of >7 tag substring