1

各文に含まれる単語の数を数える方法にこだわっています。この例は次のとおりです。次のstring sentence = "hello how are you. I am good. that's good." ようになります。

//sentence1: 4 words
//sentence2: 3 words
//sentence3: 2 words

文の数を取得できます

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

文字列全体の単語数を取得できます

    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 + 1] == ' ')
                    {
                        count++;
                    }
                }
            } 
        }
        return count;
    }

次にボタン1

        int words = CountWord(sentance);
        label4.Text = (words.ToString());

しかし、各文にいくつの単語が含まれているか数えることはできません。

4

8 に答える 8

5

のように文字列をループする代わりに、CountWords私はただ使用します。

 int words = s.Split(' ').Length;

それははるかにクリーンでシンプルです。すべての単語の配列を返す空白で分割します。その配列の長さは、文字列内の単語の数です。

于 2012-11-21T03:27:42.027 に答える
4

代わりにSplitを使用してみませんか?

        var sentences = "hello how are you. I am good. that's good.";

        foreach (var sentence in sentences.TrimEnd('.').Split('.'))
            Console.WriteLine(sentence.Trim().Split(' ').Count());
于 2012-11-21T03:28:57.463 に答える
1

各文の単語数が必要な場合は、次のことを行う必要があります。

string s = "This is a sentence. Also this counts. This one is also a thing.";
string[] sentences = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string sentence in sentences)
{
    Console.WriteLine(sentence.Split(' ').Length + " words in sentence *" + sentence + "*");
}
于 2012-11-21T03:30:25.597 に答える
1

Use CountWord on each element of the array returned by s.Split:

string sentence = "hello how are you. I am good. that's good.";
string[] words = sentence.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length;

for (string sentence in sentences)
{
    int noOfWordsInSentence = CountWord(sentence);
}
于 2012-11-21T03:32:14.693 に答える
1
string text = "hello how are you. I am good. that's good.";
string[] sentences = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
IEnumerable<int> wordsPerSentence = sentences.Select(s => s.Trim().Split(' ').Length);
于 2012-11-21T03:33:23.060 に答える
1

ここのいくつかの回答で述べたように、Split、Trim、Replace などの文字列関数を見てください。ここでのすべての回答で簡単な例が解決されますが、正しく分析できない可能性のある文がいくつかあります。

"Hello, how are you?" (no '.' to parse on)
"That apple costs $1.50."  (a '.' used as a decimal)
"I   like     whitespace    .    "   
"Word"  
于 2012-11-21T03:34:50.517 に答える
-1

Does your spelling of sentence in:

int words = CountWord(sentance);

have anything to do with it?

于 2012-11-21T03:30:46.160 に答える