Here are some other
String
methods for finding characters or substrings within a string. 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, and 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 you only need to know that the string contains a character sequence, but the precise location isn't important.The following table describes the various string search methods.
Method | Description |
---|---|
int indexOf(int ch) | Returns the index of the first (last) occurrence of the specified character. |
int indexOf(int ch, int fromIndex) | Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index. |
int indexOf(String str) | Returns the index of the first (last) occurrence of the specified substring. |
int indexOf(String str, int fromIndex) | Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index. |
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.