I am a bit new to Objective C and was wondering if there is a better way to count words in a string.
ie:
NSString *str = @\"this is a string\";
// r
Unless you're going to be doing it hundreds of times a second, I would just opt for the readable solution, something like the following pseudocode:
def count (str):
lastchar = " "
count = 0
for char as every character in string:
if char is not whitespace and lastchar is whitespace:
count = count + 1
lastchar = char
return count
It seems a bit of a waste to create a whole array of other strings just so you can count them and throw them away.
And if, for some reason, it becomes an issue, you can just replace the function body with a faster version. Make sure it is a problem first however. Optimisation of code that's fast enough already is wasted effort.