小编Dar*_*3ss的帖子

计算每个句子中的单词数量

我不知道如何计算每个句子中有多少单词,这样做的一个例子就是:string sentence = "hello how are you. I am good. that's good." 让它像:

//sentence1: 4 words
//sentence2: 3 words
//sentence3: 2 words
Run Code Online (Sandbox Code Playgroud)

我可以得到句子的数量

    public int GetNoOfWords(string s)
    {
        return s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
    label2.Text = (GetNoOfWords(sentance).ToString());
Run Code Online (Sandbox Code Playgroud)

我可以得到整个字符串中的单词数

    public int CountWord (string text)
    {
        int count = 0;
        for (int i = 0; i < text.Length; i++)
        {
            if (text[i] != ' ')
            {
                if ((i + 1) == text.Length)
                {
                    count++;
                }
                else
                {
                    if(text[i + …
Run Code Online (Sandbox Code Playgroud)

c#

-2
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1