This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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().)