There are multiple ways in which you can check if a Java String contains another String as a Sub-String or not, we take a look at 4 such examples.
Example 1: Using contains() method
package org.code2care.examples;
public class ExampleSubString {
public static void main(String[] args) {
String str = "This is my String!";
String subStr = "my";
if(str.contains(subStr)) {
System.out.println("String contains substring!: " + subStr);
} else {
System.out.println("String does not contain substring!: " + subStr);
}
}
}
Example 2: Using contains() with ignore case
If you want to ignore the case for the match, make both strings lower cases or upper cases while doing the check.
if(str.toLowerCase().contains(subStr.toLowerCase())) {
System.out.println("String contains substring!: " + subStr);
} else {
System.out.println("String does not contain substring!: " + subStr);
}
if(str.toUpperrCase().contains(subStr.toUpperrCase())) {
System.out.println("String contains substring!: " + subStr);
} else {
System.out.println("String does not contain substring!: " + subStr);
}
Example 3: Using Regular Expression
package org.code2care.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExampleRegexMatch {
public static void main(String... args) {
String str = "This is my String!";
String subStr = "My";
String regexPattern = "(?i)" + Pattern.quote(subStr);
Pattern pattern = Pattern.compile(regexPattern);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("String contains substring!: " + subStr);
} else {
System.out.println("String does not contain substring!: " + subStr);
}
}
}
Example 4: Using indexOf()
public static void main(String... args) {
String str = "This is my String!";
String subStr = "This";
int index = str.indexOf(subStr);
if (index != -1) {
System.out.println("String contains substring at index " + index + ": " + subStr);
} else {
System.out.println("String does not contain substring: " + subStr);
}
}
Output:
Further Reading & References:
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!