【问题标题】:How can I make it so that text.Split(' ')[0] increments?我怎样才能使 text.Split(\' \')[0] 递增?
【发布时间】:2022-12-12 13:49:28
【问题描述】:

我怎样才能使 text.Split(' ')[0] 递增?我希望它执行 text.Split(' ')[++] 但是把那个 ++ 放在那里是行不通的。目标是让代码对“搜索”字词进行计数。抱歉,C# 新手。

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";

            // skip whitespace until first word

            while (index < text.Length)
            {
                if (search == text.Split(' ')[0])
                {
                    wordCount++;
                }
            }
            Console.WriteLine(wordCount);
        }
    }
}

【问题讨论】:

  • text.Split(' ')[0] 返回一个字符串。你不能使用++,除非它是一个数字
  • .Split 返回一个数组,数组有一个.Length 属性。你是在问如何遍历数组吗?

标签: c#


【解决方案1】:

你可以这样做:

string text = "I ate a donut on national donut day and it tasted like a donut";
string search = "donut";

int wordCount = text.Split(' ').Count(x => x == search);

Console.WriteLine(wordCount);

这给出了3

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2011-01-10
    • 2019-01-01
    相关资源
    最近更新 更多