String handling is one of the most essential concepts in Java, and searching within strings is a common task. In this post, we'll dive into the various string-searching methods available in Java. These methods help us locate specific characters, substrings, or patterns within a given string.
String Searching Methods in Java with Examples
1. Searching for a Character or Substring
indexOf(int ch) and indexOf(int ch, int fromIndex)
These methods search for the first occurrence of a specified character or substring.
Example:
String str = "JavaGuides";
int index = str.indexOf('a');
// Result: 1
2. Searching for the Last Occurrence
lastIndexOf(int ch) and lastIndexOf(int ch, int fromIndex)
They search for the last occurrence of a specified character or substring, starting from the end of the string. Again, the fromIndex parameter can specify where the search begins.
Example:
String str = "JavaGuides";
int index = str.lastIndexOf('a');
// Result: 3
3. Checking If a String Contains a Sequence
contains(CharSequence sequence)
This method returns true if the string contains the specified sequence of char values.
Example:
String str = "JavaGuides";
boolean result = str.contains("Guides");
// Result: true
4. Checking Prefix and Suffix
startsWith(String prefix) and endsWith(String suffix)
These methods check whether the string starts or ends with the specified prefix or suffix.
Example:
String str = "JavaGuides";
boolean startsWith = str.startsWith("Java");
// Result: true
boolean endsWith = str.endsWith("Guides");
// Result: true
5. Matching Regular Expressions
matches(String regex)
This method tells whether or not the string matches the given regular expression.
Example:
String str = "12345";
boolean result = str.matches("\\d+");
// Result: true
Summary
Java provides a wide range of methods to perform various searching tasks within strings. From locating a single character to matching intricate regular expressions, the functionalities are rich and robust.
Here's a quick summary table for reference:
Related Blog Posts
- Java StringBuffer: Methods, Examples, and Performance Tips
- Java StringBuffer Class API Guide
- When to Use String, StringBuffer, and StringBuilder in Java
- String vs StringBuffer in Java with Example (Performance Analysis)
- Java StringBuilder: Basics, Methods, Examples, Performance Tips
- Java String: A Guide to String Basics, Methods, Immutability, Performance, and Best Practices
- Java String Class API Guide - Covers all the String Methods
- Best Way to Reverse a String in Java
- Guide to Java String Constant Pool
- Guide to String Best Practices in Java (Best Practice)
Comments
Post a Comment
Leave Comment