Search code examples
javanumberswords

What's Wrong? Number Of Words In a Sentence Java


int numOfWords = str.length() - str.replace(" ", "").length();

Why does that not work? If str is equal to "Hello bye", numOfWords should equal 2, but when ran numOfWords equals 0. Any help would be greatly appreciated!


Solution

  • You are only replacing one blank, so the output will be 1 (at least this is what is produce in my JVM)

    If you want to know the number of words then either add 1 to this number or use

    str.split(" ").length;