如何计算字符串中的单词数?

Tae*_*on. 0 c# string loops count cpu-word

我想计算字符串中的单词数。就像如果给定一个字符串:

string str = "Hello! How are you?";
Run Code Online (Sandbox Code Playgroud)

那么输出将是:

Number of words in string “Hello! How are you?” is 4.
Run Code Online (Sandbox Code Playgroud)

我正在使用 for 循环,这些是我当前的代码。

    string wordCountStr = "";
    int noOfWords = 0;
    private void btn_Computate4_Click(object sender, EventArgs e)
    {
        wordCountStr = tb_Qns4Input.Text.ToString(); //tb_Qns4Input is a textbox.

        for (int i = 0; i< wordCountStr.Length; i++)
        {
            //I don't know how to code here.
        }

        lbl_ResultQns4.Text = "Number of words in string " + wordCountStr + " is " + noOfWords;
    }
Run Code Online (Sandbox Code Playgroud)

哦,是的,我正在使用 Microsoft Visual Studio 2013 进行工作。所以代码在按钮点击事件下。

另外:使用“foreach”、“for 循环”、“do/while”循环和“while”循环进行编码有哪些不同的方法?我只能将这 4 个循环用于我的工作。

我已经通过使用这些代码解决了这个问题:

    string wordCountStr = "";
    int noOfWords = 0;
    private void btn_Computate4_Click(object sender, EventArgs e)
    {
        wordCountStr = tb_Qns4Input.Text.ToString();
        foreach (string sentence in wordCountStr.TrimEnd('.').Split('.'))
        {
            noOfWords = sentence.Trim().Split(' ').Count();
        }


        lbl_ResultQns4.Text = "Number of words in ''" + wordCountStr + "'' is " + noOfWords;
    }
Run Code Online (Sandbox Code Playgroud)

Dav*_*ton 5

假设完美的输入,您可以简单地分割空间,然后获得Length结果数组的 。

int count = wordCountStr.Split(' ').Length;
Run Code Online (Sandbox Code Playgroud)