Friday, 14 June 2013

Searching String - lastIndexOf()

To search for the last occurence of a specific character  in the string , lastIndexOf() function is used.This function returns an integer type value ,it returns the last occurrence of the specified character in the string.The charcter should be written in single quote
Syntax:    Stringname.lastIndexOf('ChararacterToBeSearched');

The same function can be used to search for a particular string in a complete string.The string is always written in double quotes.This function will return he last occurence of the string in the complete string.If the string 
Syntax :   Stringname.lastIndexOf("StringToBeSearched");

If you want to search for a character after a particular number of characters, then the start index is also given along with the character, when the program is compiled by Java complier , compiler donot search for the specified character upto that index number specified by you.
Syntax:  Stringname.lastIndexOf('ChararacterToBeSearched',StartIndex);

In the same way if you want to search a string or a word in the string to be searched then the start index is given along with the string to be searched. Compler during compiling donot search forthe string upto that index numbered entered.
Syntax::   Stringname.lastIndexOf("StringToBeSearched",StartIndex);

Program for lastIndexOf()


class Last
{
public static void main(String arg[]) 
{
String s= "this is the duty of every citizen of india to serve his country at the cost of anything";
System.out.println(s);

System.out.println(s.indexOf('o'));
System.out.println(s.lastIndexOf('o'));

System.out.println(s.indexOf("the"));
System.out.println(s.lastIndexOf("the"));

System.out.println(s.indexOf("o",10));
System.out.println(s.lastIndexOf('o',60));

System.out.println(s.indexOf("the",10));
System.out.println(s.lastIndexOf("the",60));

}
}

Output of the above code is :


No comments:

Post a Comment

full details in json
Proudly Powered by Blogger.
back to top