Java String Search Methods Explained
In Java, there are several methods for searching strings.
- indexOf() returns the position index of the first occurrence of a specified character or substring in the original string. If not found, it returns -1.
- lastIndexOf(): Returns the index position of the last occurrence of a specified character or substring within the original string. If not found, returns -1.
- contains(): Determines whether the original string contains the specified character or substring. The return value is a boolean, true if it contains and false if it does not.
- Check if the original string starts with the specified character or substring. The method returns a boolean value, true if it does start with the specified character or substring, false if it does not.
- endsWith() method checks whether the original string ends with a specified character or substring. It returns a boolean value, true if the string ends with the specified character or substring, false if not.
- matches(): Determines whether the original string matches the specified regular expression. The return value is a boolean type, where true indicates a match and false indicates no match.
- split(): splits the original string into an array of strings based on a specified regular expression.
- substring(): Extracts a substring from the original string. You can specify both the starting and ending index, or just the starting index.
- replace() function: used to replace specified characters or substrings in the original string with new characters or substrings.
- replaceAll(): Replace all characters or substrings in the original string that match the specified regular expression with a new character or substring.
- replaceFirst(): Replaces the first character or substring in the original string that matches the specified regular expression with a new character or substring.
The above are common methods for searching strings, choose the appropriate method based on specific needs to search strings.