数组列表& contains() - 不区分大小写

发布于 2024-09-05 02:31:45 字数 71 浏览 1 评论 0原文

我希望 ArrayList 中的 contains() 方法不区分大小写。

有什么办法吗?

谢谢

I want the contains() method from ArrayList to be case insensitive.

Is there any way?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

断舍离 2024-09-12 02:31:45

不可以。您必须定义自己的 contains 方法,该方法必须在 ArrayList 之间进行迭代,并使用 String 的 equalsIgnoreCase 方法比较值> 类。

编辑:我不想粗鲁,但问题很清楚:这个人想要使用 contains 方法。因此,由于太多原因,他不能/应该在添加元素之前使用 toLowerCase:例如,他可能需要原始的 String (而不是小写的) 。另外,当我们讨论 contains 方法时,我们关注的是元素而不是它们的索引(正如有人在几分钟前回答的那样)。

No. You will have to define your own contains method that will have to iterate among the ArrayList and compare the values using the equalsIgnoreCase method of the String class.

Edit: I don't want to be rude, but the question is pretty clear: the guy wants to use the contains method. So he can't/should use toLowerCase before adding the elements because of too many reasons: for example, he could need the original String (not the one that is lowercased). Also, as we are talking about the contains method, we are focusing on the elements rather than their indexes (as someone answered some minutes ago).

猛虎独行 2024-09-12 02:31:45

正如@Cristian 所说,没有本地方法可以实现这一点。我想我应该发布我编写的小实用方法,以防它是有用的复制和粘贴:

public static boolean ContainsCaseInsensitive(ArrayList<String> searchList, String searchTerm)
{
    for (String item : searchList)
    {
        if (item.equalsIgnoreCase(searchTerm)) 
            return true;
    }
    return false;
}

As @Cristian has said, there is no native method to achieve this. I thought I'd post the small utility method that I wrote in case it's a useful copy-and-paste:

public static boolean ContainsCaseInsensitive(ArrayList<String> searchList, String searchTerm)
{
    for (String item : searchList)
    {
        if (item.equalsIgnoreCase(searchTerm)) 
            return true;
    }
    return false;
}
德意的啸 2024-09-12 02:31:45

我遇到了这样的问题,我使用了 BinarySearch 的解决方法,它似乎有效:

ArrayList al= new ArrayList();
al.Add("Elem1");
al.Add("Elem5");
al.Add("Elem3");
al.Sort();  

if (al.BinarySearch("elem3", new CaseInsensitiveComparer()) > 0)
      MessageBox.Show("Exists");   //this case
else
      MessageBox.Show("Not found");  

I had a problem like this, and I used this workaround with BinarySearch that seems to work:

ArrayList al= new ArrayList();
al.Add("Elem1");
al.Add("Elem5");
al.Add("Elem3");
al.Sort();  

if (al.BinarySearch("elem3", new CaseInsensitiveComparer()) > 0)
      MessageBox.Show("Exists");   //this case
else
      MessageBox.Show("Not found");  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文