How to Check if a String Contains Another Substring in Java


In this example we will show two different methods to determine whether a string contains another string in Java.

Source Code

1) Using Contains() Function

package com.beginner.examples;
public class CheckerExample1 {

    public static void main(String[] args) {

        String str = "I am a student in University";

//Case-sensitive:
        String substr = "student";
        if (str.contains(substr)) {
            System.out.println(substr + ": found (case-sensitive)");
        } else {
            System.out.println(substr + ": not found (case-sensitive)");
        }
        substr = "UNIVERSITY";        
        if (str.contains(substr)) {
            System.out.println(substr + ": found (case-sensitive)");
        } else {
            System.out.println(substr + ": not found (case-sensitive)");
        }

//Case-insensitive:        
        if (str.toLowerCase().contains(substr.toLowerCase())) {
            System.out.println(substr + ": found (case-insensitive)");
        } else {
            System.out.println(substr + ": not found (case-insensitive)");
        }
    }
}

Output:

student: found  (case-sensitive)
UNIVERSITY: not found  (case-sensitive)
UNIVERSITY: found (case-insensitive)

2) Using indexOf() Function

package com.beginner.examples;
public class CheckerExample2 {

    public static void main(String[] args) {

        String str = "I am a beginner in Java programming";

//Case-sensitive:
        String substr = "beginner";
        if (str.indexOf(substr) != 0) {
            System.out.println(substr + ": found (case-sensitive)");
        } else {
            System.out.println(substr + ": not found (case-sensitive)");
        }
        substr = "JAVA";        
        if (str.contains(substr)) {
            System.out.println(substr + ": found (case-sensitive)");
        } else {
            System.out.println(substr + ": not found (case-sensitive)");
        }

//Case-insensitive:        
        if (str.toLowerCase().indexOf(substr.toLowerCase()) != 0) {
            System.out.println(substr + ": found (case-insensitive)");
        } else {
            System.out.println(substr + ": not found (case-insensitive)");
        }
    }
}

Output:

beginner: found  (case-sensitive)
JAVA: not found  (case-sensitive)
JAVA: found (case-insensitive)

Tips

From the examples above, we can see that string and substring should be converted to the same case before a case-insensitive check.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments