How do I count the number of words in a string?

后端 未结 8 1639
感情败类
感情败类 2021-01-13 02:54

I need to count the number of words and I am assuming the correct way to do it is by calculating the number of times that the previous character in a string is not a letter

8条回答
  •  春和景丽
    2021-01-13 03:16

    This problem is slightly more complicated than your algorithm allows.

    • What if there are two or more spaces in a row?
    • What if the string starts or ends with whitespace (or non-word characters)?

    This looks like homework, so I don't want to provide any code. I suggest an alternative approach which is simpler to think about.

    • Walk through the characters in the string, one by one.
    • Do something to remember if you are currently scanning a word or if you are not currently scanning a word.
    • Do something to determine when you enter or leave a word, and increment your counter accordingly.

提交回复
热议问题