Counting words in a string?

后端 未结 4 466
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 07:32

Hello for this program I am supposed to count the number of words in a string. So far, I have found out how to find the number of characters in a string but am unable to figure

4条回答
  •  星月不相逢
    2021-01-23 07:38

    Hints only since this is probably homework.

    What you're looking to count is the number of transitions between 'word' characters and whitespace. That will require remembering the last character and comparing it to the current one.

    If one is whitespace and the other is not, you have a transition.

    With more detail, initialise the lastchar to whitespace, then loop over every character in your input. Where the lastchar was whitespace and the current character is not, increase the word count.

    Don't forget to copy the current character to lastchar at the end of each loop iteration. And it should hopefully go without saying that the word count should be initialised to 0.

提交回复
热议问题