MY mENU


Thursday, 9 February 2012

Search characters and substrings in Strings


The String Class provides accessor methods that return the position within the String of a specific character or substring: indexOf() and lastIndexOf().

- The indexOf() methods search forward from the beginning of the String.

- The lastIndexOf() methods search backward from the end of the String.

If a character or substring is not found, indexOf() and lastIndexOf() return -1.

- The String Class also provides a search method, contains, that returns true if the String contains a particular character sequence. Use this method when only need to know that theString contains a character sequence, but the precise location isn't important.

1. int indexOf(int ch)/int lastIndexOf(int ch) : Returns the index of the first (last) occurrence of the specified character.

2. int indexOf(int ch, int fromIndex)/int lastIndexOf(int ch, int fromIndex) : Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.

3. int indexOf(String str)/int lastIndexOf(String str) : Returns the index of the first (last) occurrence of the specified substring.

4. int indexOf(String str, int fromIndex)/int lastIndexOf(String str, int fromIndex) : Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index

5. boolean contains(CharSequence s) : Returns true if the string contains the specified character sequence.

Note: CharSequence is an interface that is implemented by the String class. Therefore, you can use a string as an argument for the contains() method.

No comments:

Post a Comment