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

如何统计指定字符串在C#字符串数组中的出现次数?

C#控制台程序:统计输入名称的出现次数

需求说明

用户编写的程序支持多次输入名称,输入No时停止输入,之后需要统计用户指定名称在之前输入内容中的出现次数,目前已能获取查询名称,但不清楚统计逻辑的实现方式。

修改后的完整代码

Console.WriteLine("Here you can write the name as many as you want, and if u wanna end up just write No!");
Console.WriteLine();
Console.WriteLine("Start writing a name:");

string[] namnArray = new string[200];
int inputCount = 0; // 记录有效输入的名称数量(排除终止符No)
for (int i = 0; i < namnArray.Length; i++)
{
    Console.ForegroundColor = ConsoleColor.Yellow;
    string input = Console.ReadLine();
    Console.ForegroundColor = ConsoleColor.White;

    if (input == "No")
    {
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Magenta;
        Console.WriteLine("write a name of your choice:");
        string yourChoice = Console.ReadLine();

        // 统计目标名称的出现次数
        int count = 0;
        // 只遍历实际输入的有效内容,跳过空元素和No
        for (int j = 0; j < inputCount; j++)
        {
            // 如需忽略大小写,可替换为 namnArray[j].Equals(yourChoice, StringComparison.OrdinalIgnoreCase)
            if (namnArray[j] == yourChoice)
            {
                count++;
            }
        }

        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine($"The name '{yourChoice}' appears {count} times.");
        break; // 终止循环,结束程序
    }

    // 非终止符则存入数组并计数
    namnArray[i] = input;
    inputCount++;
    Console.Write("Do u wanna write another one?  ");
}

关键实现细节

  • 排除终止符:提前判断输入是否为No,避免将终止标识存入数组,保证统计数据的准确性。
  • 有效输入计数:用inputCount记录用户实际输入的有效名称数量,遍历数组时只处理已输入的内容,跳过未使用的空元素。
  • 统计逻辑:通过循环遍历有效输入的元素,逐个与查询名称对比,累加匹配次数;如果使用LINQ可以简化为一行代码(需引用System.Linq):
    int count = namnArray.Take(inputCount).Count(name => name == yourChoice);
    
  • 终止循环:完成统计后用break跳出循环,避免程序继续执行后续不必要的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:55:23