Count how many words in each sentence

后端 未结 8 2045
耶瑟儿~
耶瑟儿~ 2021-01-17 05:55

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 ha

相关标签:
8条回答
  • 2021-01-17 06:18

    As noted in several answers here, look at String functions like Split, Trim, Replace, etc to get you going. All answers here will solve your simple example, but here are some sentences which they may fail to analyse correctly;

    "Hello, how are you?" (no '.' to parse on)
    "That apple costs $1.50."  (a '.' used as a decimal)
    "I   like     whitespace    .    "   
    "Word"  
    
    0 讨论(0)
  • 2021-01-17 06:20
    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);
    
    0 讨论(0)
  • 2021-01-17 06:24

    If you want number of words in each sentence, you need to

    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 + "*");
    }
    
    0 讨论(0)
  • 2021-01-17 06:25

    Does your spelling of sentence in:

    int words = CountWord(sentance);
    

    have anything to do with it?

    0 讨论(0)
  • 2021-01-17 06:27

    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);
    }
    
    0 讨论(0)
  • 2021-01-17 06:35

    If you only need a count, I'd avoid Split() -- it takes up unnecessary space. Perhaps:

    static int WordCount(string s)
    {
        int wordCount = 0;
        for(int i = 0; i < s.Length - 1; i++)
            if (Char.IsWhiteSpace(s[i]) && !Char.IsWhiteSpace(s[i + 1]) && i > 0)
                wordCount++;
        return ++wordCount;
    }
    
    public static void Main()
    {
        Console.WriteLine(WordCount(" H elloWor    ld g  ")); // prints "4"
    }
    

    It counts based on the number of spaces (1 space = 2 words). Consecutive spaces are ignored.

    0 讨论(0)
提交回复
热议问题