You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何在单个单词数组中查找目标短语的索引

查找完整短语在单词数组中的连续索引

给定单词数组:

string[] myWords = { "Arizona", "District", "Court", "is", "located", "at", ".", "District", "court", "closed" };

需要找到完整短语 "Arizona District Court" 对应的连续索引(预期结果 [0,1,2]),需忽略仅部分匹配的片段(如索引7、8的"District Court",因缺少前置的"Arizona")。

原代码问题分析

你提供的循环逻辑完全偏离需求:

foreach (var word in myWords)
{
    if (myWords.Any(word.ToLowerInvariant().Contains))
    {
        var wordIndex = word;
    }
}

这段代码只是检查数组中是否存在包含当前单词小写形式的元素,既没有处理连续单词的短语匹配,也没有正确记录索引,自然会返回所有相关单词的匹配项,而非完整短语的连续索引。

正确实现方案

核心思路是:遍历数组的起始位置,检查从该位置开始的连续单词是否与目标短语完全匹配(支持大小写不敏感),匹配成功则收集对应索引。

代码示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] myWords = { "Arizona", "District", "Court", "is", "located", "at", ".", "District", "court", "closed" };
        string[] targetPhrase = { "Arizona", "District", "Court" };
        List<int> result = new List<int>();

        // 遍历所有可能的起始索引,确保剩余单词数足够容纳目标短语
        for (int startIndex = 0; startIndex <= myWords.Length - targetPhrase.Length; startIndex++)
        {
            bool isMatch = true;
            // 逐个比较对应位置的单词(忽略大小写)
            for (int i = 0; i < targetPhrase.Length; i++)
            {
                if (!string.Equals(myWords[startIndex + i], targetPhrase[i], StringComparison.OrdinalIgnoreCase))
                {
                    isMatch = false;
                    break;
                }
            }

            if (isMatch)
            {
                // 收集匹配的连续索引
                for (int i = 0; i < targetPhrase.Length; i++)
                {
                    result.Add(startIndex + i);
                }
                // 若只需第一个匹配项,可在此处break终止循环
                break;
            }
        }

        // 输出结果
        Console.WriteLine($"result = [{string.Join(",", result)}]");
    }
}

代码逻辑说明

  1. 边界控制:外层循环的终止条件为 startIndex <= myWords.Length - targetPhrase.Length,避免索引越界,确保从startIndex开始有足够的单词匹配目标短语。
  2. 大小写不敏感匹配:使用StringComparison.OrdinalIgnoreCase进行单词比较,兼容示例中索引8的小写"court"这类情况。
  3. 索引收集:一旦找到完整匹配,将这段连续的索引全部加入结果列表,若只需第一个匹配项,找到后可直接跳出循环提升效率。

内容的提问来源于stack exchange,提问作者AlexFF1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:40:47