方法一:使用String的indexOf()方法

String的indexOf()方法可以用于判斷一個字符串是否包含另一個字符。該方法返回包含字符的索引值,如果不存在則返回-1。

String str = "Hello World!";
char ch = 'o';
if (str.indexOf(ch) != -1) {
    System.out.println("字符串中包含字符'" + ch + "'");
} else {
    System.out.println("字符串中不包含字符'" + ch + "'");
}

方法二:使用String的contains()方法

String的contains()方法可以直接判斷一個字符串是否包含另一個字符串。該方法返回一個布爾值,如果包含則返回true,否則返回false。

String str = "Hello World!";
String substring = "o";
if (str.contains(substring)) {
    System.out.println("字符串中包含子字符串'" + substring + "'");
} else {
    System.out.println("字符串中不包含子字符串'" + substring + "'");
}

方法三:使用Regex正則表達式判斷

使用正則表達式也可以判斷字符串是否包含某個字符??梢允褂谜齽t表達式的匹配方法如matches()、find()等。

使用matches()方法:

String str = "Hello World!";
String regex = ".*o.*";
if (str.matches(regex)) {
    System.out.println("字符串中包含字符'o'");
} else {
    System.out.println("字符串中不包含字符'o'");
}

使用find()方法:

String str = "Hello World!";
String regex = "o";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    System.out.println("字符串中包含字符'o'");
} else {
    System.out.println("字符串中不包含字符'o'");
}

方法四:使用StringTokenizer切割字符串

使用StringTokenizer可以將字符串按指定的分隔符切割成多個部分,然后判斷其中是否包含某個字符。

String str = "Hello World!";
StringTokenizer st = new StringTokenizer(str, " ");
boolean containsChar = false;
while (st.hasMoreTokens()) {
    String token = st.nextToken();
    if (token.contains("o")) {
        containsChar = true;
        break;
    }
}
if (containsChar) {
    System.out.println("字符串中包含字符'o'");
} else {
    System.out.println("字符串中不包含字符'o'");
}

方法五:使用字符數(shù)組遍歷判斷

可以將字符串轉(zhuǎn)換為字符數(shù)組,然后遍歷數(shù)組判斷是否包含某個字符。

String str = "Hello World!";
char ch = 'o';
char[] charArray = str.toCharArray();
boolean containsChar = false;
for (char c : charArray) {
    if (c == ch) {
        containsChar = true;
        break;
    }
}
if (containsChar) {
    System.out.println("字符串中包含字符'" + ch + "'");
} else {
    System.out.println("字符串中不包含字符'" + ch + "'");
}

方法六:使用Java 8的Stream流判斷

使用Java 8的Stream流可以輕松判斷字符串是否包含某個字符。

String str = "Hello World!";
char ch = 'o';
boolean containsChar = str.chars().anyMatch(c -> c == ch);
if (containsChar) {
    System.out.println("字符串中包含字符'" + ch + "'");
} else {
    System.out.println("字符串中不包含字符'" + ch + "'");
}

方法七:使用Apache Commons Lang庫判斷

Apache Commons Lang是一個開源的Java類庫,提供了很多常用的工具類,包括StringUtils類可以用來判斷字符串是否包含某個字符。

String str = "Hello World!";
char ch = 'o';
boolean containsChar = StringUtils.contains(str, ch);
if (containsChar) {
    System.out.println("字符串中包含字符'" + ch + "'");
} else {
    System.out.println("字符串中不包含字符'" + ch + "'");
}

總結(jié)

本文介紹了使用不同方法來判斷字符串是否包含某個字符的七種方式,包括使用String的indexOf()方法、contains()方法、Regex正則表達式、StringTokenizer切割字符串、字符數(shù)組遍歷、Java 8的Stream流和Apache Commons Lang庫。根據(jù)實際情況選擇合適的方法來判斷字符串是否包含某個字符,可以提高代碼的效率和可讀性。