You need to enable JavaScript to run this app. C# 对比数组元素末尾字符并查找对应匹配项索引实现求助
优惠活动
大模型
产品
解决方案
定价
更多

C# 对比数组元素末尾字符并查找对应匹配项索引实现求助

C# 实现数组元素末尾匹配并获取索引的方案

方案1:基础for循环实现(无额外依赖,性能最优)

你原有代码的问题在于直接调用Substring没有校验字符串长度,当数组元素长度小于目标匹配串长度时会抛出越界异常。改用for循环可以直接获取索引,同时增加边界校验逻辑:

using System;

class Program
{
    static void Main()
    {
        string[] lista = {"item_100", "item_200", "item_300"};
        string input = "300";
        int matchLength = input.Length; // 自动取目标串长度,不需要硬编码3

        // 遍历同时获取索引
        for (int i = 0; i < lista.Length; i++)
        {
            string current = lista[i];
            // 先校验长度,避免越界
            if (current.Length >= matchLength)
            {
                // 也可以直接用内置方法判断结尾:if (current.EndsWith(input))
                string suffix = current.Substring(current.Length - matchLength);
                if (suffix == input)
                {
                    Console.WriteLine("\nFound: {0}, index: {1}", suffix, i);
                    // 如果只需要找第一个匹配项,这里加break即可
                }
            }
        }
    }
}

方案2:LINQ 链式实现(代码更简洁)

如果可以用LINQ,用带索引的Select重载可以快速筛选匹配项和对应索引:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] lista = {"item_100", "item_200", "item_300"};
        string input = "300";

        var matches = lista.Select((val, idx) => new { val, idx })
                           .Where(x => x.val.Length >= input.Length && x.val.EndsWith(input))
                           .ToList();

        foreach (var match in matches)
        {
            Console.WriteLine("\nFound: {0}, index: {1}", match.val, match.idx);
        }
    }
}

注意事项

  • 优先使用内置的EndsWith方法,不需要手动切割字符串,既简化代码也避免手动计算长度出错
  • 大小写不敏感匹配可以指定比较规则:current.EndsWith(input, StringComparison.OrdinalIgnoreCase)
  • 如果只需要获取第一个匹配项的索引,可以直接用Array.FindIndex方法:
int firstMatchIndex = Array.FindIndex(lista, s => s.Length >= input.Length && s.EndsWith(input));

内容的提问来源于stack exchange,提问作者What am I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 18:03:02