There are multiple ways to compare certain segments of a string in Java:
- Using the substring() method: The substring() method returns a new string that is a substring of the original string. We can use this method to extract the desired segment of the string and compare it using the equals() method.
Example:
String str = "Hello World";
String subStr = str.substring(0, 5); // Extracting the first 5 characters
if (subStr.equals("Hello")) {
// Do something
}
- Using regular expressions: Regular expressions provide a powerful mechanism to match specific patterns of characters within a string. We can use the matches() method to check if the string matches a specified regular expression pattern.
Example:
String str = "Hello World";
if (str.matches("^Hello.*")) { // Checking if the string starts with "Hello"
// Do something
}
- Using StringIndexOutOfBoundsException: We can use the charAt() method to access individual characters of the string and compare them using conditional operators. We can also use the length() method to ensure that the comparison does not go out of bounds.
Example:
String str = "Hello World";
int len = str.length();
if (len >= 5 && str.charAt(4) == 'o' && str.charAt(3) != 'l') {
// Do something
}