Java - 在字符串数组中搜索字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38334208/
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
Java - search a string in string array
提问by Hari M
In java do we have any method to find that a particular string is part of string array. I can do in a loop which I would like to avoid.
在java中,我们有什么方法可以找到特定字符串是字符串数组的一部分。我可以在我想避免的循环中进行。
e.g.
例如
String [] array = {"AA","BB","CC" };
string x = "BB"
I would like a
我想要一个
if (some condition to tell whether x is part of array) {
do something
} else {
do something else
}
采纳答案by ΦXoc? ? Пepeúpa ツ
Do something like:
做类似的事情:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
因为如果字符串 x 存在于数组中,则返回 true (现在转换为列表...)
Example:
例子:
if(Arrays.asList(array).contains(x)){
// is present ... :)
}
回答by VatsalSura
This code will work for you:
此代码将为您工作:
bool count = false;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(x))
{
count = true;
break;
}
}
if(count)
{
//do some other thing
}
else
{
//do some other thing
}
回答by Arthur Noseda
You could also use the commons-langlibrary from Apache which provides the much appreciated method contains
.
您还可以使用Apache的commons-lang库,它提供了非常受欢迎的方法contains
。
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}