Java String Search Methods Explained

In Java, there are several methods for searching strings.

  1. 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.
  2. lastIndexOf(): Returns the index position of the last occurrence of a specified character or substring within the original string. If not found, returns -1.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. split(): splits the original string into an array of strings based on a specified regular expression.
  8. substring(): Extracts a substring from the original string. You can specify both the starting and ending index, or just the starting index.
  9. replace() function: used to replace specified characters or substrings in the original string with new characters or substrings.
  10. replaceAll(): Replace all characters or substrings in the original string that match the specified regular expression with a new character or substring.
  11. 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.

bannerAds