Java – Check if a String contains a substring

In Java, we can use String.contains() to check if a String contains a substring.

1. String.contains() – Case Sensitive

JavaExample1.java

package com.mkyong;

public class JavaExample1 {

    public static void main(String[] args) {

        String name = "mkyong is learning Java 123";

        System.out.println(name.contains("Java"));      // true
        System.out.println(name.contains("java"));      // false
        System.out.println(name.contains("MKYONG"));    // false
        System.out.println(name.contains("mkyong"));    // true

        if (name.contains("Java")) {
            System.out.println("Hello Java");
        } else {
            System.out.println("abc...");
        }
        
    }

}

Output


true
false
false
true
Hello Java

2. String.contains() – Ignoring Case

The idea is to convert all the strings and substring to lowercase before check with .contains()

JavaExample2.java

package com.mkyong;

public class JavaExample2 {

    public static void main(String[] args) {

        String name = "mkyong is learning Java 123";

        System.out.println(containsIgnoreCase(name, "Java"));      // true
        System.out.println(containsIgnoreCase(name, "java"));      // true
        System.out.println(containsIgnoreCase(name, "MKYONG"));    // true
        System.out.println(containsIgnoreCase(name, "mkyong"));    // true

    }

    public static boolean containsIgnoreCase(String str, String subString) {
        return str.toLowerCase().contains(subString.toLowerCase());
    }

}

Output


true
true
true
true

3. indexOf()

3.1 Review the JDK String source code, the contains() uses indexOf() to check substring internally.

String.java

package java.lang;

	public boolean contains(CharSequence s) {
        return indexOf(s.toString()) >= 0;
    }

3.2 So, we can also check the substring like this :

JavaExample3.java

package com.mkyong;

public class JavaExample3 {

    public static void main(String[] args) {

        String name = "mkyong is learning Java 123";

        if (name.indexOf("Java") != -1) {
            System.out.println("Hello Java"); // print this
        } else {
            System.out.println("abc...");
        }

    }

}

Output


Hello Java

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar