在 Java 中,可以使用以下幾種方法來判斷一個字符串是否在數(shù)組中:文章來源:http://www.zghlxwxcb.cn/news/detail-625827.html
- 使用 for 循環(huán)遍歷數(shù)組,逐個比較字符串是否相等。
String[] arr = {"apple", "banana", "orange"};
String target = "apple";boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(target)) {
found = true;
break;
}
}
if (found) {
System.out.println("Found the target string in the array.");
} else {
System.out.println("Could not find the target string in the array.");
}
- 使用 Arrays.asList() 將數(shù)組轉換為列表,然后使用列表的 contains() 方法來判斷字符串是否在數(shù)組中。
import java.util.Arrays;
import java.util.List;
String[] arr = {"apple", "banana", "orange"};
String target = "apple";
List<String> list = Arrays.asList(arr);
if (list.contains(target)) {
System.out.println("Found the target string in the array.");
} else {
System.out.println("Could not find the target string in the array.");
}
- 使用 Java 8 的 Stream API,使用 anyMatch() 方法來判斷是否存在符合條件的元素。
import java.util.Arrays;
String[] arr = {"apple", "banana", "orange"};
String target = "apple";
boolean found = Arrays.stream(arr).anyMatch(s -> s.equals(target));
if (found) {
System.out.println("Found the target string in the array.");
} else {
System.out.println("Could not find the target string in the array.");
}
請注意,在 Java 中,字符串的比較應使用 equals() 方法,而不是 == 運算符。文章來源地址http://www.zghlxwxcb.cn/news/detail-625827.html
到了這里,關于java 怎么判斷某個字符串是否在數(shù)組中的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!