Counting words in a string


#1

Hello!

I want to count how many words are in a String. I've iterated through the string to count the spaces as in the code below....


// Check if String has contents
        if (arrayOfStrings[i].isNotEmpty())
        {
            // Must have a word if not empty
            int numberOfWords = 1;

            // Retreive String from StringArray
            String stringToCheck = arrayOfStrings[i];

            // Loop through all letters and count words
            for (int b=0; b<arrayOfStrings[i].length(); b++)
            {
                if (stringToCheck[b] == juce_wchar(" "))
                {
                    numberOfWords++;
                }
            }

            // If word count exceeded then delete String
            if (numberOfWords > noWords)
                arrayOfStrings.set(i, "");
        }

 Apart from the fact it desn't work :-p I read in the docs that accessing the character using the [] operator is a bad idea. What would be a better approach to conting the words in a String?

Cheers


#2

http://www.juce.com/juce/api/classStringArray.html#a2996bff706bcf449fbdab264c266307a


#3

Awesome, just what I needed thanks.