杰瑞科技汇

Java字符串contains方法如何精确匹配子串?

Of course! In Java, there are several ways to check if a string contains another string. The most common and direct method is the String.contains() method.

Java字符串contains方法如何精确匹配子串?-图1
(图片来源网络,侵删)

Here’s a detailed breakdown of the different ways, from the simplest to more advanced use cases.


The String.contains() Method (Most Common)

This is the most straightforward and readable way to check if one string is a substring of another. It returns a boolean value: true if the sequence of characters is found, and false otherwise.

Syntax

public boolean contains(CharSequence sequence)
  • sequence: The character sequence (usually a String) to search for.
  • Return Value: true if the string contains the specified sequence, false otherwise.
  • Case-Sensitive: This check is case-sensitive. "Java" is not the same as "java".

Example

public class ContainsExample {
    public static void main(String[] args) {
        String mainString = "Hello, welcome to the world of Java programming!";
        String subString1 = "Java";
        String subString2 = "java";
        String subString3 = "Python";
        String subString4 = "world";
        // Check if mainString contains subString1
        boolean containsJava = mainString.contains(subString1);
        System.out.println("Does the string contain 'Java'? " + containsJava); // Output: true
        // Check if mainString contains subString2 (case-sensitive)
        boolean containsJavaLower = mainString.contains(subString2);
        System.out.println("Does the string contain 'java'? " + containsJavaLower); // Output: false
        // Check for a string that is not present
        boolean containsPython = mainString.contains(subString3);
        System.out.println("Does the string contain 'Python'? " + containsPython); // Output: false
        // Check for another substring that is present
        boolean containsWorld = mainString.contains(subString4);
        System.out.println("Does the string contain 'world'? " + containsWorld); // Output: true
    }
}

Using String.indexOf()

The indexOf() method returns the index of the first occurrence of the specified substring. If the substring is not found, it returns -1. You can use this to perform a "contains" check.

Syntax

public int indexOf(String str)
  • Return Value: The index of the first occurrence of the substring, or -1 if it's not found.

Example

public class IndexOfExample {
    public static void main(String[] args) {
        String mainString = "Learning Java is fun.";
        String searchFor = "Java";
        // indexOf() returns the starting index (7) if found
        int index = mainString.indexOf(searchFor);
        if (index != -1) {
            System.out.println("Found 'Java' at index: " + index);
            System.out.println("The string contains 'Java'."); // This is the check
        } else {
            System.out.println("The string does not contain 'Java'.");
        }
        // Example with a string that is not found
        String notFound = "Python";
        int indexNotFound = mainString.indexOf(notFound);
        if (indexNotFound == -1) {
            System.out.println("The string does not contain 'Python'."); // Output
        }
    }
}

Using String.matches() with Regular Expressions

The matches() method checks if the entire string matches a given regular expression. To check for a simple substring, you need to wrap your search string in (which means "any character, zero or more times").

Java字符串contains方法如何精确匹配子串?-图2
(图片来源网络,侵删)

Syntax

public boolean matches(String regex)
  • Return Value: true if the entire string matches the regular expression, false otherwise.

Example

public class MatchesExample {
    public static void main(String[] args) {
        String mainString = "The quick brown fox jumps over the lazy dog";
        // To check if "fox" is a substring, we use ".*fox.*"
        // .  -> any character
        // *  -> zero or more times
        // .*fox.* -> "anything, followed by 'fox', followed by anything"
        boolean containsFox = mainString.matches(".*fox.*");
        System.out.println("Does the string contain 'fox'? " + containsFox); // Output: true
        // Check for a word that is not present
        boolean containsCat = mainString.matches(".*cat.*");
        System.out.println("Does the string contain 'cat'? " + containsCat); // Output: false
    }
}

Note: While this works, contains() is much more efficient and readable for simple substring checks. Use matches() when you need to validate the entire string's format against a complex regular expression.


Case-Insensitive Search

If you need to perform a case-insensitive search, you can convert both strings to the same case (e.g., lowercase) before checking.

Example using toLowerCase()

public class CaseInsensitiveExample {
    public static void main(String[] args) {
        String mainString = "Hello, World!";
        String searchFor = "world";
        // Convert both strings to lowercase for comparison
        boolean containsIgnoreCase = mainString.toLowerCase().contains(searchFor.toLowerCase());
        System.out.println("Does the string contain 'world' (case-insensitive)? " + containsIgnoreCase); // Output: true
    }
}

Checking for Multiple Substrings

If you need to check if a string contains any of several substrings, you can loop through them.

Example

import java.util.Arrays;
import java.util.List;
public class MultipleContainsExample {
    public static void main(String[] args) {
        String mainString = "This is a test sentence.";
        List<String> searchStrings = Arrays.asList("test", "sample", "sentence");
        boolean found = false;
        for (String s : searchStrings) {
            if (mainString.contains(s)) {
                System.out.println("Found a match: '" + s + "'");
                found = true;
                break; // Exit loop once a match is found
            }
        }
        if (!found) {
            System.out.println("No matches found.");
        }
    }
}

Summary: Which Method to Use?

Method Use Case Performance Notes
contains() Best for most cases. Checking if a substring exists. Excellent Most readable and direct. Case-sensitive.
indexOf() When you need the position of the substring, not just a yes/no. Excellent A classic alternative. Returns -1 if not found.
matches() When you need to validate the entire string against a regex. Good for regex Overkill for simple substring checks. Less performant.
toLowerCase() When you need a case-insensitive search. Good Simple and effective.
Looping When you need to check for multiple possible substrings. Good Flexible for complex search criteria.

For your day-to-day programming, String.contains() is the tool you should reach for first.

分享:
扫描分享到社交APP
上一篇
下一篇