一、使用 String.contains() 函數判斷字符串是否包含某個字符
public class StringContainsExample {
public static void main(String[] args) {
String str = "hello world";
System.out.println(str.contains("hello")); // true
System.out.println(str.contains("Hi")); // false
}
}
String 類提供了 contains()
函數來判斷一個字符串是否包含另一個字符串。該函數返回一個 boolean 類型的值,如果包含,則返回 true,否則返回 false。
可以看到,在上面的示例中,我們判斷字符串 str
是否包含子串 "hello"
和 "Hi"
,結果分別為 true 和 false。
二、使用 String.indexOf() 函數判斷字符串是否包含某個字符
public class StringIndexOfExample {
public static void main(String[] args) {
String str = "hello world";
System.out.println(str.indexOf("world")); // 6
System.out.println(str.indexOf("Java")); // -1
}
}
還可以使用 indexOf()
函數來查找一個字符串是否包含另一個字符串。如果包含,則返回子串的起始位置,否則返回 -1。
在上面的示例中,我們判斷了字符串 str
是否包含子串 "world"
和 "Java"
,結果分別為 6 和 -1。
三、使用正則表達式判斷字符串是否包含某個字符
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String str = "hello world";
Pattern pattern = Pattern.compile("hello");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("Found!");
} else {
System.out.println("Not found.");
}
}
}
還可以使用正則表達式來判斷字符串是否包含某個字符。通過編譯正則表達式,並使用 Matcher 類來匹配字符串,如果字符串包含正則表達式所描述的字符,則返回 true,否則返回 false。
在上面的示例中,我們使用正則表達式 "hello"
來匹配字符串 str
,如果匹配成功,則輸出 “Found!”,否則輸出 “Not found.”
四、使用 Java 8 Stream API 判斷字符串是否包含某個字符
import java.util.Arrays;
public class StreamExample {
public static void main(String[] args) {
String str = "hello world";
boolean result = Arrays.stream(str.split(" ")).anyMatch("hello"::equals);
if (result) {
System.out.println("Found!");
} else {
System.out.println("Not found.");
}
}
}
如果使用 Java 8 或以上的版本,還可以使用 Stream API 來判斷字符串是否包含某個字符。通過使用 split()
函數將字符串分割成字符串數組,然後使用 anyMatch()
函數來判斷是否存在相應的字符串。
在上面的示例中,我們對字符串 str
使用空格進行分割,然後使用 anyMatch()
函數來判斷是否存在子串 "hello"
。輸出結果同之前的示例。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/289586.html