算上每个句子多少单词 [英] Count how many words in each sentence

查看:100
本文介绍了算上每个句子多少单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我卡上怎么算多少字在每个句子,这样的一个例子是:串句=。你好你怎么样我好那好
,并让它出来,如:

  // SENTENCE1:4个字
// SENTENCE2:3个字
// sentence3:2字

我可以得到数句子

 公众诠释GetNoOfWords(字符串s)
{
返回s.Split(新的char [ ] {''},StringSplitOptions.RemoveEmptyEntries)。长度;
}
label2.Text =(GetNoOfWords(森泰斯)的ToString());

和我能得到的话整串


$的数量b $ b

 公众诠释CountWord(字符串文本)
{
诠释计数= 0;
的for(int i = 0; I< text.Length;我++)
{
如果(文[I] =''!)
{
如果(第(i + 1)== text.Length)
{
计数++;
}
,否则
{
如果(文[I + 1] =='')
{
计数++;
}
}
}
}
返回计数;
}



然后按钮1

  INT字= CountWord(森泰斯); 
label4.Text =(words.ToString());

的我不能指望有多少词在每个句子。


解决方案

为什么不使用拆分呢?




  VAR语句=。你好你怎么样我好这是好的; 

的foreach(在sentences.TrimEnd VAR句(。)。斯普利特('。'))
Console.WriteLine(sentence.Trim()。斯普利特('').Count之间());



I'm stuck on how to count how many words are in each sentence, an example of this is: string sentence = "hello how are you. I am good. that's good." and have it come out like:

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

I can get the number of sentences

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

and i can get the number of words in the whole string

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

then button1

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

But I can't count how many words are in each sentence.

解决方案

Why not use Split instead?

        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());

这篇关于算上每个句子多少单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆