杰瑞科技汇

Java中String的contains方法如何使用?

Of course! In Java, there are several ways to check if a String contains another sequence of characters (a substring). The most common and recommended method is the String.contains() method.

Java中String的contains方法如何使用?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the main methods, with examples and explanations.


The contains() Method (Most Common)

This is the simplest and most direct way to check for a substring. It returns true if the sequence of characters is found in the string, and false otherwise.

Syntax

public boolean CharSequence contains(CharSequence s)
  • CharSequence is an interface that String implements, so you can pass a String directly.
  • The check is case-sensitive.

Example

public class ContainsExample {
    public static void main(String[] args) {
        String sentence = "Java is a powerful programming language.";
        // Check if the string contains "powerful"
        boolean hasPowerful = sentence.contains("powerful");
        System.out.println("Does the sentence contain 'powerful'? " + hasPowerful); // true
        // Check if the string contains "Python"
        boolean hasPython = sentence.contains("Python");
        System.out.println("Does the sentence contain 'Python'? " + hasPython); // false
        // Case-sensitive check
        boolean hasJava = sentence.contains("java"); // lowercase 'j'
        System.out.println("Does the sentence contain 'java'? " + hasJava); // false
        boolean hasJavaCapital = sentence.contains("Java"); // uppercase 'J'
        System.out.println("Does the sentence contain 'Java'? " + hasJavaCapital); // true
    }
}

When to Use It:

  • When you only need to know if a substring exists (true or false).
  • This is the go-to method for most use cases.

The indexOf() Method

The indexOf() method finds the starting index of the first occurrence of a substring. If the substring is not found, it returns -1. You can use this to check for containment.

Syntax

public int indexOf(String str)

Example

public class IndexOfExample {
    public static void main(String[] args) {
        String sentence = "Java is a powerful programming language.";
        // Find the index of "powerful"
        int index1 = sentence.indexOf("powerful");
        System.out.println("Index of 'powerful': " + index1); // 11
        // Find the index of "Python"
        int index2 = sentence.indexOf("Python");
        System.out.println("Index of 'Python': " + index2); // -1
        // Check for containment by comparing the result to -1
        if (sentence.indexOf("Java") != -1) {
            System.out.println("The sentence contains 'Java'."); // This will print
        }
        if (sentence.indexOf("python") != -1) { // case-sensitive
            System.out.println("The sentence contains 'python'."); // This will NOT print
        }
    }
}

When to Use It:

  • When you need to know where the substring is located (its index).
  • It's a good alternative if you're working with older Java codebases or need the index for other operations.

The matches() Method (Regular Expressions)

The matches() method checks if the entire string matches a given regular expression (regex). To check if a string contains a pattern, you must use (which means "any character, zero or more times") before and after your search pattern.

Java中String的contains方法如何使用?-图2
(图片来源网络,侵删)

Syntax

public boolean String matches(String regex)

Example

public class MatchesExample {
    public static void main(String[] args) {
        String sentence = "Java is a powerful programming language.";
        // Check if the sentence contains the word "powerful"
        // The ".*" before and after makes the check for "anywhere in the string"
        boolean containsPowerful = sentence.matches(".*powerful.*");
        System.out.println("Contains 'powerful' using regex? " + containsPowerful); // true
        // Check if it contains a digit (e.g., from "Java 11")
        boolean containsDigit = sentence.matches(".*\\d.*"); // \d is a regex for a digit
        System.out.println("Contains a digit? " + containsDigit); // false
        // This is NOT what you want for simple containment!
        // This checks if the ENTIRE string is exactly "Java".
        boolean isExactlyJava = sentence.matches("Java");
        System.out.println("Is the sentence exactly 'Java'? " + isExactlyJava); // false
    }
}

When to Use It:

  • When your search is more complex and requires pattern matching (e.g., finding an email format, a phone number, or any sequence that follows a specific rule).
  • Avoid using matches() for simple substring checks, as it's less efficient and more verbose than contains().

Using java.util.regex.Pattern and java.util.regex.Matcher

This is a more powerful and flexible way to work with regular expressions, especially if you need to find multiple matches or get more information about the match.

Example

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexMatcherExample {
    public static void main(String[] args) {
        String sentence = "Java is fun, and Java is powerful.";
        // Compile the regex pattern
        Pattern pattern = Pattern.compile("Java"); // The word "Java"
        // Create a matcher for the input string
        Matcher matcher = pattern.matcher(sentence);
        // find() searches for the next subsequence that matches the pattern
        boolean found = matcher.find();
        System.out.println("Did we find 'Java'? " + found); // true
        // You can also find all occurrences
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.println("Found '" + matcher.group() + "' at index " + matcher.start());
        }
        System.out.println("Total occurrences of 'Java': " + count); // 2
    }
}

When to Use It:

  • When you need to perform complex pattern searches.
  • When you need to find all occurrences of a pattern and iterate over them.
  • When you need to extract specific groups from the matched text.

Summary and Comparison

Method Return Type Use Case Key Feature
contains() boolean Simple containment check. Easiest and most readable for a simple "yes/no" check.
indexOf() int Finding the position of a substring. Returns -1 if not found, so you can use it for a boolean check.
matches() boolean Checking if the entire string matches a regex. Powerful but overkill for simple substring checks. Requires for containment.
Pattern.matcher() boolean (via find()) Advanced regex searches. Most flexible. Can find all matches and get detailed match information.

Best Practice

For checking if a String contains another String, always prefer String.contains(). It is the most readable, concise, and idiomatic way to perform this task in modern Java.

Java中String的contains方法如何使用?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇