I have to pass a string to a method and return the count of words within the String. The issue I'm having is how to ignore ALL whitespace while counting the words.
While doing some searching I see that most people are using a String array to count words so that is what I have written so far.
My questions are:
1) Can I do this without using an array and just using a for loop / if else combination?
2) How do I dump All of the whitespace. My array solution appears to work fine until the # of spaces between the words increases.
On your original string, first call trim() to remove trailing/heading spaces, then you can use the replaceAll method on your trimmed string to replace multiple spaces into single spaces. Finally do the split the way you're currently doing.
Your regular expression is wrong. It only replaces 2 spaces by one; instead you want something more generic that replace ANY number of 1 or more spaces by just one space. Look into regular expression characters like ? and *
Also, you're not assigning the results of the replaceAll method to anything, for instance str = str.replaceAll(); You can also combine method calls on one line like this: String result = mystring.trim().replaceAll().split().
Koen Aerts wrote:On your original string, first call trim() to remove trailing/heading spaces, then you can use the replaceAll method on your trimmed string to replace multiple spaces into single spaces. Finally do the split the way you're currently doing.
Praveen Kumar M K wrote:
Yes, you could use a short hand character like \s and replace 1 or many space occurrences with just 1 space.
There's no need for any replaceAll() step. Just trim() then split() it all that's necessary. (Or, I suppose, you skip the trim() and do a single replaceAll() followed by split().)
I am afraid that code has some problems. One is that it is pure procedural code, with no object‑oriented features. Maybe one can count words in a procedural style, but the technique with String#split does use an object and its features.
Another problem is that the loop is to say the least awkward, starting at 0 and then testing whether the index is > 0. I would regard that as poor quality code for a language like Java®.