xorebxebx
I know you are an industry flunky, but that does not mean everything that spouts out of you is correct.
First off, yours is
not a single pass, unless your
split algorithm is really smart (meaning it has a tradeoff on memory usage).
Secondly, three passes over an array is significantly cheaper than memory allocation and copying -- something you should know.
Third off, having a bug in the initial attempt doesn't validate any argument, either for or against -- and it is a logical fallacy to present it as such.
Fourth off, C++ wasn't designed to look pretty on one line. Format that function nicely and it would pass code reviews easily:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
size_t CountWords( std::string s )
{
// If the string contains only whitespace, then there are no words.
//
// Otherwise:
// number of words := number of whitespace sequences - leading whitespace + trailing whitespace
//
return ((size_t)std::count_if( s.begin(), s.end(), std::ptr_fun <int, int> ( std::isspace ) ) == s.length())
? 0
: std::count_if(
std::find_if(
s.begin(),
s.end(),
std::not1( std::ptr_fun <int, int> ( std::isspace ) )
),
std::unique(
s.begin(),
std::replace_copy_if(
s.begin(),
s.end(),
s.begin(),
std::ptr_fun <int, int> ( std::isspace ),
' '
)
),
std::ptr_fun <int, int> ( std::isspace )
)
+ !std::isspace( *s.rbegin() );
}
| |
(Properly formatting it made me notice one more thing that was missing... which is why I originally said
four passes...)
Finally, you are the one who started this "trivial issue". But there you have erred on arrogance again: it is
not a trivial issue. Counting patterns in data is a very complex subject -- again something you should know.
So spend your hatred elsewhere.
Oh, BTW, I fixed a bug in your code. (Pay attention to the regexp):
|
def countWords(str: String) = str.split("\\s+").size
| |
Alas. I've had enough of this now.