我有一个字符串,我对其使用 split 函数,以便将其拆分为不同的部分。 然后我想检查数组是否包含某个值,我尝试使用 for 循环并将数组转换为列表并使用包含选项,但我得到相同的结果 - 文本不在数组中。
附注 我编辑了代码以展示更好的示例。
String categories = "C1-C-D-A-1-В";
String[] cat = categories.split("-");
String catCode = "B";
//always return false
if (Arrays.asList(cat).contains(catCode))
{
//do somthing
}
for (int idxCat = 0; idxCat < cat.length; idxCat++) {
//always return false
if ((cat[idxCat]).equals(catCode))
{
//do somthing
break;
}
}
最佳答案
我对您所问的问题做了一个快速演示。
如果您尝试查看数组中的任何字符串是否包含特定值:
public class HelloWorld
{
public static void main(String[] args)
{
String[] strings = new String[] {"bob", "joe", "me"};
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains("bob"))//doing "b" will also find "bob"
{
System.out.println("Found it!");
}
}
}
}
控制台输出是:找到它!
我建议尝试使用评论中提到的 equalsIgnoreCase() 。您可能还想显示数组中的值:
import java.util.Arrays;
public class HelloWorld
{
public static void main(String[] args)
{
String[] strings = new String[] {"bob", "joe", "me"};
System.out.println(Arrays.toString(strings));
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains("bob"))
{
System.out.println("Found it!");
}
}
}
}
输出:
[bob, joe, me]
Found it!
这可以帮助您确定数组中字符串中的值是否实际上是您认为的值。
关于java - Java中拆分后比较数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542144/