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

时间:2014-06-04 13:11:36

标签: c# string loops count word

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

string str = "Hello! How are you?";

输出将是:

Number of words in string “Hello! How are you?” is 4.

我正在使用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;
    }

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

增加: 使用'foreach','for loops','do / while'循环和&amp;编码的不同方法有哪些? '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;
    }

1 个答案:

答案 0 :(得分:4)

假设完美输入,你可以在空格上split,然后获得结果数组的Length

int count = wordCountStr.Split(' ').Length;