Java Beginner - Counting number of words in sentence

后端 未结 17 1668
忘了有多久
忘了有多久 2021-01-01 05:29

I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn\'t work. No matter what I write, I on

17条回答
  •  囚心锁ツ
    2021-01-01 06:01

    Please check for boundary conditions at str.charAt(i+1). It can result in a StringIndexOutOfBoundsException when the string is terminated by a space.

    1. Account for cases where the string starts with a ' '
    2. The String could be blank.
    3. The definition of a 'word' could differ. For example - '1 2'. Are 1,2 words ?

    I know you do not want an alternate method but string.split(" ").length() is an easier way to start.

提交回复
热议问题