Searching Strings
The String class provides two methods that allow you to search a string for a specified character or substring:
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
- indexOf() Searches for the first occurrence of a character or substring.
- lastIndexOf() Searches for the last occurrence of a character or substring.
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
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment
Please Write a Message for Programming or something Related issues.