public class StringInArrayExample {
public static void main(String[] args) {
// 定义一个字符串数组
String[] array = {"apple", "banana", "orange", "grape"};
// 要查找的字符串
String target = "orange";
// 判断字符串是否在数组中
boolean isExist = contains(array, target);
// 输出结果
if (isExist) {
System.out.println("字符串 '" + target + "' 在数组中。");
} else {
System.out.println("字符串 '" + target + "' 不在数组中。");
}
}
// 方法:判断字符串是否在数组中
public static boolean contains(String[] array, String target) {
for (String element : array) {
if (element.equals(target)) {
return true;
}
}
return false;
}
}
array
。target
,例如 "orange"
。contains
的方法,该方法遍历数组中的每个元素,并使用 equals
方法检查是否与目标字符串相等。如果找到匹配项,则返回 true
,否则返回 false
。contains
方法的返回值,输出相应的消息,告知用户目标字符串是否存在于数组中。通过这种方式,你可以轻松判断一个字符串是否存在于指定的字符串数组中。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站