一、使用String類的contains方法
Java中最簡單的判斷字符串是否包含指定字符的方法是使用String類的contains方法。該方法接收一個字符串參數,返回一個boolean類型的值,表示目標字符串中是否包含參數字符串。
String str = "hello world";
boolean contains = str.contains("llo");
System.out.println(contains); // true
如果只需要判斷單個字符是否包含在字符串中,可以將字符轉換為字符串進行判斷:
String str = "hello world";
boolean contains = str.contains(Character.toString('h'));
System.out.println(contains); // true
二、使用String類的indexOf方法
除了contains方法外,String類還提供了indexOf方法,也可以用於判斷字符串中是否包含指定字符。該方法接收一個字符參數,返回該字符在目標字符串中第一次出現的位置,如果沒有找到,則返回-1。
String str = "hello world";
int index = str.indexOf('o');
if(index != -1) {
System.out.println("字符串中包含'o'字符");
} else {
System.out.println("字符串中不包含'o'字符");
}
可以通過遍歷目標字符串的每一個字符,逐個判斷是否與目標字符相等來實現判斷字符串中是否包含指定字符的功能。
String str = "hello world";
char target = 'o';
boolean contains = false;
for(char c: str.toCharArray()) {
if(c == target) {
contains = true;
break;
}
}
System.out.println(contains); // true
三、使用正則表達式
Java中還可以使用正則表達式來判斷字符串中是否包含指定字符。通過使用正則表達式中的字符集,可以匹配字符串中的任意一個字符。
String str = "hello world";
boolean contains = str.matches(".*o.*");
System.out.println(contains); // true
其中".*"表示匹配任意字符,0個或多個。使用"."需要注意轉義,因為"."在正則表達式中表示匹配任意單個字符。
四、使用Java 8 Stream API
Java 8中引入的Stream API也提供了判斷字符串中是否包含指定字符的方法。通過將字符串轉換為字符流,可以使用anyMatch方法進行判斷。
String str = "hello world";
boolean contains = str.chars().anyMatch(c -> c == 'o');
System.out.println(contains); // true
可以使用filter方法對字符進行篩選,再使用count方法獲取字符數來實現字符出現次數的統計。
String str = "hello world";
long count = str.chars().filter(c -> c == 'o').count();
System.out.println("字符'o'在字符串中出現了" + count + "次");
原創文章,作者:NKJY,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/144206.html