杰瑞科技汇

Java字符串包含方法有哪些?

Of course! The phrase "contains Java string" can mean a few different things. I'll cover the most common interpretations, from the basic Java method to more advanced concepts.

Java字符串包含方法有哪些?-图1
(图片来源网络,侵删)

The Most Common Meaning: Using the .contains() Method

This is almost certainly what you're looking for. The .contains() method is used to check if a specific sequence of characters (a substring) exists within another string.

Key Details:

  • What it does: It returns true if the sequence of characters is found, and false otherwise.
  • Case-Sensitive: The check is case-sensitive. For example, searching for "java" in "Java is fun" will return false.
  • Return Type: boolean (true or false).
  • Argument: It takes a CharSequence as an argument, which is a flexible interface that includes String, StringBuilder, CharBuffer, etc. You will most often pass a String.

Syntax:

boolean contains(CharSequence sequence)

Example:

Let's say you want to check if a user's comment contains the word "spam".

public class ContainsExample {
    public static void main(String[] args) {
        String userComment = "This product is amazing, but the shipping was spammy.";
        // Check if the comment contains the word "spam"
        boolean hasSpam = userComment.contains("spam");
        System.out.println("The original comment is: \"" + userComment + "\"");
        System.out.println("Does it contain the word 'spam'? " + hasSpam); // Output: true
        // Example where it's not found
        String anotherComment = "This is a great product.";
        boolean hasSpam2 = anotherComment.contains("spam");
        System.out.println("\nThe original comment is: \"" + anotherComment + "\"");
        System.out.println("Does it contain the word 'spam'? " + hasSpam2); // Output: false
        // Example of case-sensitivity
        String javaText = "I love learning about Java.";
        boolean hasJava = javaText.contains("java"); // This will be false
        System.out.println("\nThe original text is: \"" + javaText + "\"");
        System.out.println("Does it contain 'java'? " + hasJava); // Output: false
    }
}

Other Ways to "Contain" a String

Sometimes you need to do more than just check for a simple substring. Here are other common scenarios.

A. Checking for Multiple Substrings (Using )

If you want to check if a string contains any of several possible substrings, you can chain the .contains() method with the logical OR operator ().

Java字符串包含方法有哪些?-图2
(图片来源网络,侵删)
public class MultipleContainsExample {
    public static void main(String[] args) {
        String logMessage = "User attempted to access forbidden resource.";
        boolean containsError = logMessage.contains("error") || logMessage.contains("exception");
        boolean containsForbidden = logMessage.contains("forbidden");
        System.out.println("Log Message: " + logMessage);
        System.out.println("Is it an error or exception? " + containsError); // false
        System.out.println("Does it mention 'forbidden'? " + containsForbidden); // true
    }
}

B. Case-Insensitive Check

To perform a case-insensitive search, you can convert both the main string and the search term to the same case (e.g., lowercase) before checking.

public class CaseInsensitiveExample {
    public static void main(String[] args) {
        String text = "The quick Brown Fox jumps over the lazy dog.";
        // Convert both to lowercase for a case-insensitive check
        boolean hasFox = text.toLowerCase().contains("fox");
        System.out.println("Original Text: " + text);
        System.out.println("Does it contain 'fox' (case-insensitive)? " + hasFox); // true
    }
}

C. Checking if a String Starts or Ends with a Substring

Java also has dedicated methods for these specific checks.

  • .startsWith(String prefix): Checks if the string begins with the specified prefix.
  • .endsWith(String suffix): Checks if the string ends with the specified suffix.
public class StartsWithEndsWithExample {
    public static void main(String[] args) {
        String fileName = "document_final_report.pdf";
        boolean isReport = fileName.startsWith("document");
        boolean isPdf = fileName.endsWith(".pdf");
        System.out.println("File Name: " + fileName);
        System.out.println("Does it start with 'document'? " + isReport); // true
        System.out.println("Does it end with '.pdf'? " + isPdf); // true
    }
}

Advanced: Using Regular Expressions (Pattern Matching)

For very complex "contains" logic (e.g., checking for an email format, a phone number, or any pattern), you should use regular expressions with the Pattern and Matcher classes.

This is more powerful but also more complex.

Java字符串包含方法有哪些?-图3
(图片来源网络,侵删)

Example: Check if a string contains a digit.

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexContainsExample {
    public static void main(String[] args) {
        String input1 = "Password123";
        String input2 = "Password";
        // Compile a regular expression pattern: "\\d" means "any digit"
        Pattern pattern = Pattern.compile("\\d");
        Matcher matcher1 = pattern.matcher(input1);
        Matcher matcher2 = pattern.matcher(input2);
        // The find() method searches the string for the pattern
        boolean hasDigit1 = matcher1.find();
        boolean hasDigit2 = matcher2.find();
        System.out.println("Input: " + input1 + " -> Contains a digit? " + hasDigit1); // true
        System.out.println("Input: " + input2 + " -> Contains a digit? " + hasDigit2); // false
    }
}

Summary Table

Method What it Does Example
str.contains("sub") Checks if str has the exact sequence "sub". "hello".contains("ell") -> true
str.toLowerCase().contains("sub") Case-insensitive check for "sub". "Hello".toLowerCase().contains("ell") -> true
str.startsWith("pre") Checks if str begins with "pre". "prefix".startsWith("pre") -> true
str.endsWith("suf") Checks if str ends with "suf". "suffix".endsWith("fix") -> true
Pattern.compile("regex").matcher(str).find() Uses powerful regular expressions to find a pattern. Pattern.compile("\\d").matcher("a1b").find() -> true
分享:
扫描分享到社交APP
上一篇
下一篇