1.效率最高(最原始) 代码如下(示例): public class Demo { public static boolean useLoop(String[] arr, String targetValue) {
public class Demo {
public static boolean useLoop(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue)) return true;
}
return false;
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useLoop(arr, targetValue));
}
}
import java.util.Arrays;
public class Demo {
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useList(arr, targetValue));
}
}
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static boolean useSet(String[] arr, String targetValue) {
Set
return set.contains(targetValue);
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useSet(arr, targetValue));
}
}
import java.util.Arrays;
public class Demo {
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if (a > 0) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useArraysBinarySearch(arr, targetValue));
}
}
来源地址:https://blog.csdn.net/xijinno1/article/details/131692680
--结束END--
本文标题: java判断某个字符串是否在字符串数组中的方法(4种)
本文链接: https://www.lsjlt.com/news/395382.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0