java判断字符串在数组中
在 Java 中,如果你想要判断一个字符串是否存在于字符数组中,可以使用 `contains()` 方法或者遍历数组。以下是两种常见的做法:
1. 使用 `contains()` 方法: ```java String[] array = {"apple", "banana", "cherry"}; String strToFind = "banana"; boolean found = Arrays.asList(array).contains(strToFind); if (found) { System.out.println("The string is in the array."); } else { System.out.println("The string is not in the array."); } ``` 这里我们先将数组转换成列表,因为 `contains()` 方法在原生数组上不可用。
2. 遍历数组: ```java String[] array = {"apple", "banana", "cherry"}; String strToFind = "orange"; // 假设你想找的不是数组里的元素 for (String element : array) { if (element.equals(strToFind)) { System.out.println("The string is in the array."); } } ``` 如果找到匹配项,就立即结束循环并输出信息。
