Powered by Blogger.

Tuesday 20 September 2016

Searching Strings

No comments :
The String class provides two methods that allow you 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 on failure.
To search for the first occurrence of a character use

To search for the last occurrence of a character, use

Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use

Here, startIndex specifies the index at which point the search begins. for indexOf(), the search runs from startIndex to the end of the string. for lastIndexOf(), the search runs from startIndex to zero.
The following example shows how to use the various index methods to search inside of a string:

output:
Now is the time for all good mento come to the aid of their country.
indexOf(t)=7
lastIndexOf(t)=64
indexOd(the)=7
lastIndexOf(the)=54
indexOf(t,10)=11
lastIndexOf(t, 60)=54

No comments :

Post a Comment

Please Write a Message for Programming or something Related issues.