java 如何用java中的字符串数组检查字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6881979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check string with array of strings in java?
提问by shiva
HI I want to check one string value with an array of strings. I am using the contains()
method, but it is case sensitive. For example:
嗨,我想用一组字符串检查一个字符串值。我正在使用该contains()
方法,但它区分大小写。例如:
String str="one";
String [] items= {"ONE","TWO","THREE"};
str.contains(items); // it is returning false.
Now the question is how to check that string ?
现在的问题是如何检查该字符串?
can anyone help me?
谁能帮我?
thanks in advance
提前致谢
回答by Joonas Pulakka
You probably want to know if itemscontain str? And be case-insensitive. So loop through the array:
您可能想知道items 是否包含str?并且不区分大小写。所以循环遍历数组:
boolean contains = false;
for (String item : items) {
if (str.equalsIgnoreCase(item)) {
contains = true;
break; // No need to look further.
}
}
回答by Anantha Sharma
you could sort the string first using stringArray=Arrays.sort(stringArray);
you can then use the Binary Search algorithm int pos = Arrays.binarySearch(stringArray, stringItem);
. if (pos > -1)
then you found the element else the stringItem
doesnot exist in the stringArray
.
您可以先使用stringArray=Arrays.sort(stringArray);
然后使用二进制搜索算法对字符串进行排序int pos = Arrays.binarySearch(stringArray, stringItem);
。if (pos > -1)
然后你发现元素 elsestringItem
不存在于stringArray
.
回答by Petar Ivanov
If you will only check once:
如果您只检查一次:
String str="one"; String [] items= {"ONE","TWO","THREE"};
for(String s : items){
if(s.compareToIgnoreCase(str) == 0){
System.out.println("match");
}
}
If you will do many checks:
如果您要进行多次检查:
String str="one"; String [] items= {"ONE","TWO","THREE"};
List<String> lowerItems = new ArrayList<String>();
for(String s : items)
lowerItems.add(s.toLowerCase());
if(lowerItems.contains(str))
System.out.println("match");