Java provides several built-in methods within the String class to efficiently search for characters or substrings within a larger string. These methods allow you to locate positions, verify content, and check boundaries. Key String Search Methods
indexOf(String str) / indexOf(char ch): Finds the index of the first occurrence of a specified character or substring. Returns -1 if not found.
lastIndexOf(String str) / lastIndexOf(char ch): Finds the index of the last occurrence of a specified character or substring, searching backward.
contains(CharSequence s): Returns a boolean (true/false) indicating whether the string contains a specific sequence of characters.
startsWith(String prefix): Checks if the string begins with a specified prefix.
endsWith(String suffix): Checks if the string ends with a specified suffix. Example Usage
String text = “Hello, CodeSignal learners!”; // Finding the first occurrence int index = text.indexOf(“CodeSignal”); // Output: 7 // Checking if a substring exists boolean hasHello = text.contains(“Hello”); // Output: true // Checking start/end boolean starts = text.startsWith(“Hello”); // Output: true Use code with caution. Important Considerations
Index-Based: indexOf methods return the integer index (starting from 0) of the first character of the match. Case Sensitivity: All search methods are case-sensitive.
Substring Handling: If a search string is not found, indexOf returns -1.
For more complex scenarios, such as pattern matching, you might use regular expressions (Pattern and Matcher classes), but the methods above are best for basic substring or character searches.
If you can tell me what specific kind of pattern you are looking for, or if you need to replace or remove the matched string, I can provide more specific code examples. Substring search in Java – string – Stack Overflow
Leave a Reply