Java: Check if a String contains another Sub-String with Examples


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);
        }
    }
}

Note: (?i) in a regular expression pattern, which is a flag to indicate a case-insensitive match. You can remove it if you want to do a case-sensitive match.


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:

String contains substring at index 0: This


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap