如何向 Array.IndexOf 添加不区分大小写的选项

发布于 2024-12-28 11:21:13 字数 413 浏览 2 评论 0原文

我有一个字符串:

string str = "hello";

和一个数组:

string[] myarr = new string[] {"good", "Hello", "this", "new"};

与我的字符串(“hello”)比较(不使用循环)时,我需要从数组中获取(“Hello”)的索引。

我尝试过:

int index = Array.IndexOf(myarr, str);

由于大写“H”,这将返回 -1,但我想要结果 1

我什至尝试过使用 StringComparer.OrdinalIgnoreCase 但无济于事。

I have a string:

string str = "hello";

And an array:

string[] myarr = new string[] {"good", "Hello", "this", "new"};

I need to get the index of ("Hello") from the array when comparing with my string ("hello") (without using a loop).

I have tried:

int index = Array.IndexOf(myarr, str);

This returns -1, because of the capital "H", but I want a result of 1.

I have even tried with StringComparer.OrdinalIgnoreCase but no avail.

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

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

发布评论

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

评论(7

佞臣 2025-01-04 11:21:14

当心!!
标记为解决方案的答案可能存在一些问题,例如:

string array[] = {"hello", "hi", "bye" , "welcome" , "hell"}

如果您使用相同的方法(如答案中所述)查找单词“hell”的索引:

int indexOfArray = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >= 0);

您将得到结果indexOfArray = 0 而不是 4

相反,使用:

Array.FindIndex(array, t => t.Equals("hell", StringComparison.InvariantCultureIgnoreCase));

以获得正确的结果。

Beaware!!
The answer marked as a solution might have some problem, like with:

string array[] = {"hello", "hi", "bye" , "welcome" , "hell"}

If you use the same method (as described in the answer) to find the index of word "hell":

int indexOfArray = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >= 0);

you will get the result indexOfArray = 0 instead of 4.

Instead use:

Array.FindIndex(array, t => t.Equals("hell", StringComparison.InvariantCultureIgnoreCase));

to get a proper result.

伪心 2025-01-04 11:21:14

由于您正在寻找索引。试试这个方法。

Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >=0);

Since you are looking for index. Try this way.

Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >=0);
不弃不离 2025-01-04 11:21:14

Array.IndexOf 调用默认的“Equals”方法,该方法区分大小写。试试这个:

Array.FindIndex(myarr, t => t.Equals(str, StringComparison.InvariantCultureIgnoreCase))

Array.IndexOf calls the default "Equals" method which is case-sensitive. Try this:

Array.FindIndex(myarr, t => t.Equals(str, StringComparison.InvariantCultureIgnoreCase))
荆棘i 2025-01-04 11:21:14
var result = myarr.FindIndex(s => s.Equals(str, StringComparison.OrdinalIgnoreCase));
var result = myarr.FindIndex(s => s.Equals(str, StringComparison.OrdinalIgnoreCase));
む无字情书 2025-01-04 11:21:14

1) 如果您只想搜索一次并希望保留源数组,可以使用此:

        public static void example1()
        {
            string[] myarr = { "good", "Hello", "this", "new" };
            var str = "new";
            var res= Array.FindIndex(myarr, x=>string.Equals(x, str, StringComparison.InvariantCultureIgnoreCase));
        }

2) 如果您要搜索多次,则最好使用此: >

public static void example1()
    {
        string[] myarr = {"good", "Hello", "this", "new"};
        var str = "new";
        var res = Array.IndexOf(Array.ConvertAll(myarr, ToStringlowerCase), str.ToLowerInvariant());
    }

3)上面的答案是不正确的:

string array[] = {"hello", "hi", "bye" , "welcome" , "hell"}
Int Indexofary = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >=0);

根本不起作用,因为它搜索的不是字符串,而是子字符串。

算法迭代数组中的单词,当获取第一个单词“hello”时,算法尝试查找“hell”的索引,该索引为 1。1 是 > >那么 0 算法就完成了,无需再进行其他操作。

如果您不想搜索子字符串但想搜索字符串,则应该修复算法。可以通过添加检查子字符串从第一个字符 t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) == 0 开始并且单词的长度等于 str.Length == t 来修复此算法.长度。固定的:

        public static int example3()
    {
        string[] myarr = { "hHello", "hi", "bye", "welcome", "hell" };
        var str = "hell";
        return Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) == 0 && str.Length == t.Length);
    }

1) if you want to search only once and want to keep source array, you can use this:

        public static void example1()
        {
            string[] myarr = { "good", "Hello", "this", "new" };
            var str = "new";
            var res= Array.FindIndex(myarr, x=>string.Equals(x, str, StringComparison.InvariantCultureIgnoreCase));
        }

2) if you will search many times it will be better to use this:

public static void example1()
    {
        string[] myarr = {"good", "Hello", "this", "new"};
        var str = "new";
        var res = Array.IndexOf(Array.ConvertAll(myarr, ToStringlowerCase), str.ToLowerInvariant());
    }

3) the answer above is incorrect :

string array[] = {"hello", "hi", "bye" , "welcome" , "hell"}
Int Indexofary = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >=0);

will not work at all, because it searches not the string, but substring.

Algorithm iterates words in array, when 1st word "hello" taken, algorithm tries to find index of 'hell' and this index is 1. 1 is > then 0 and algorithm will be finished without going to other words.

If you don't want to search substrings but want to search strings, algorythm should be fixed. This algorithm can be fixed by adding check that substring starts from 1st char t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) == 0 and the length of the words equals str.Length == t.Length. Fixed:

        public static int example3()
    {
        string[] myarr = { "hHello", "hi", "bye", "welcome", "hell" };
        var str = "hell";
        return Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) == 0 && str.Length == t.Length);
    }
痴情换悲伤 2025-01-04 11:21:14

由于 Array.IndexOf 是通用的,因此创建通用扩展函数是有意义的:

public static int IndexOf<T>(this T[] source, T value)
{
  return IndexOf<T>(source, value, StringComparison.InvariantCultureIgnoreCase);
}

public static int IndexOf<T>(this T[] source, T value, StringComparison stringComparison)
{
  if (typeof(T) == typeof(string))
    return Array.FindIndex(source, m => m.ToString().Equals(value.ToString(), stringComparison));
  else
    return Array.IndexOf(source, value);
}

Since Array.IndexOf is generic, it makes sense to make a generic extension function:

public static int IndexOf<T>(this T[] source, T value)
{
  return IndexOf<T>(source, value, StringComparison.InvariantCultureIgnoreCase);
}

public static int IndexOf<T>(this T[] source, T value, StringComparison stringComparison)
{
  if (typeof(T) == typeof(string))
    return Array.FindIndex(source, m => m.ToString().Equals(value.ToString(), stringComparison));
  else
    return Array.IndexOf(source, value);
}
属性 2025-01-04 11:21:14

我遇到了类似的问题,我需要该项目的索引,但它必须不区分大小写,我在网上浏览了几分钟,但什么也没找到,所以我只是编写了一个小方法来完成它,这就是我的方法做了:

private static int getCaseInvariantIndex(List<string> ItemsList, string searchItem)
{
    List<string> lowercaselist = new List<string>();

    foreach (string item in ItemsList)
    {
        lowercaselist.Add(item.ToLower());
    }

    return lowercaselist.IndexOf(searchItem.ToLower());
}

将此代码添加到同一个文件中,并像这样调用它:

int index = getCaseInvariantIndexFromList(ListOfItems, itemToFind);

希望这有帮助,祝你好运!

I had a similar problem, I needed the index of the item but it had to be case insensitive, i looked around the web for a few minutes and found nothing, so I just wrote a small method to get it done, here is what I did:

private static int getCaseInvariantIndex(List<string> ItemsList, string searchItem)
{
    List<string> lowercaselist = new List<string>();

    foreach (string item in ItemsList)
    {
        lowercaselist.Add(item.ToLower());
    }

    return lowercaselist.IndexOf(searchItem.ToLower());
}

Add this code to the same file, and call it like this:

int index = getCaseInvariantIndexFromList(ListOfItems, itemToFind);

Hope this helps, good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文