一、使用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-tw/n/144206.html