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

如何让text.Split(' ')[索引]递增?C#搜索词计数问题

解决C#统计指定搜索词出现次数的问题

先点明你原代码里的几个关键问题:

  • 每次循环都调用text.Split(' '),会反复生成新的单词数组,你一直取[0]永远只会对比第一个词,根本遍历不到后面的内容
  • index变量在循环里完全没有递增操作,导致while条件永远成立,程序会陷入死循环
  • 直接用Split(' ')拆分文本不严谨,遇到连续空格、开头/结尾空格时会生成空字符串,干扰统计结果

基础循环写法(适合新手理解逻辑)

先把文本一次性拆分成可靠的单词数组,再通过循环逐个比对:

using System;

namespace TESTER
{
    class Program
    {
        static void Main(string[] args)
        {
            int wordCount = 0; 
            string text = "I ate a donut on national donut day and it tasted like a donut";
            string search = "donut";

            // 按空白字符分割,自动忽略连续空格、制表符等,只保留有效单词
            string[] words = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

            // 遍历所有单词
            foreach (string word in words)
            {
                if (word == search)
                {
                    wordCount++;
                }
            }

            Console.WriteLine(wordCount); // 输出3
        }
    }
}

如果坚持想用while循环+索引的方式,可以这么写:

using System;

namespace TESTER
{
    class Program
    {
        static void Main(string[] args)
        {
            int wordCount = 0; 
            int index = 0;
            string text = "I ate a donut on national donut day and it tasted like a donut";
            string search = "donut";

            string[] words = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

            while (index < words.Length)
            {
                if (words[index] == search)
                {
                    wordCount++;
                }
                index++; // 必须手动递增索引,否则会陷入死循环
            }

            Console.WriteLine(wordCount); // 输出3
        }
    }
}

简化写法(用LINQ快速实现)

如果你想更简洁,可以用LINQ扩展方法,新手可以先做了解:

using System;
using System.Linq; // 必须添加这个命名空间

namespace TESTER
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "I ate a donut on national donut day and it tasted like a donut";
            string search = "donut";

            int wordCount = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                                .Count(word => word == search);

            Console.WriteLine(wordCount); // 输出3
        }
    }
}

另外你之前尝试的text.Split(' ')[++]是语法错误,C#不支持这种写法,正确的做法是先把拆分后的数组存为变量,再通过索引变量的递增来遍历所有元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:50:22