Searching Strings

The String class provides two methods that allow you to search a string for a specified character or sub string  index Of() Searches f!:>the first occurrence of a character or sub string. IZI Elastoplast() Searches for the last occurrence of a character or sub string. These two methods arc overloaded in several different ways. In all cases, Methodology return the index at which the character or sub string was found, or -1 on failure. To search for the first occurrence of a character, use int index Of (int let) To search for the last occurrence of a character, Use int East index Offprint) Here, ch is the character being sought.

To search for the first or last occurrence of a sub string, use int index Of(String sf) int clandestine(String str) Here, sf specifies the sub string. You can specify starting point for the search using these forms: in,t-index Of(int ell, int start Index) . int last index Of(int ch, int start Index) t int infinite(String sir, int start index  int deathless Of(String str, int start Index) Her, startle specifies the index at which point the search begins. For index Of( ), the’ search runs from start index to the end of the string. For last index Of (), the search runs from start index to zero. The following example shows how to use the various index methods to search ‘inside of Strings:

Modifying a String 

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a Suffering or use one of the following String methods, which will construct a new copy of the string with your modifications complete.

[vfb id=1]

Share This