Count words in a string method?

This would work even with multiple spaces and leading and/or trailing spaces and blank lines:

String trim = s.trim();
if (trim.isEmpty())
    return 0;
return trim.split("\\s+").length; // separate string around spaces

Hope that helps. More info about split here.

Leave a Comment