How can I count the occurrence of a word in a string?
The following function will count the occurrence of a word in a particular sentence.
Important: If the words in the string are separated (delimited ) by a comma "," or whitespace " " etc then you will have to amend the GetField function call.
If the string is "dog dog dog dog cat cat dog dog dog cat" then the words are separated by whitespaces
sSegment = GetField (sText," ", i)
If the string is "dog, dog, dog, dog, cat, cat, dog, dog, dog, cat" then the words are separated by commas
sSegment = GetField (sText,",", i)
[-] testcase Dog () appstate none [ ] [ ] INTEGER i = 0 [ ] STRING sText = "dog, dog, dog, dog, cat, cat, dog, dog, dog, cat" [ ] //STRING sText = "dog dog dog dog cat cat dog dog dog cat" [ ] [ ] STRING sFind = "dog" // substring to find occurrence off [ ] [ ] i = Occurrence(sText,sFind) [ ] Print(" The word",sFind,"appears", i , "times") [ ] [-] Integer Occurrence(STRING sText, STRING sFind) [ ] Integer i = 1,iOccurrenceOfWord = 0 [ ] String sSegment = "temp" [ ] [-] while (sSegment != "")// while we are not at the end of the string [ ] sSegment = GetField (sText,",", i) // Returns each word separately parsed by "," [ ] i++ [ ] [-] if(Trim(sSegment) == sFind) //If word is same as sFind variable [ ] iOccurrenceOfWord = iOccurrenceOfWord + 1 // Add "1" to the number of occurences [ ] [ ] return iOccurrenceOfWord
[ ] Script occurence.t - Passed [ ] Machine: (local) [ ] Started: 02:19:01PM on 18-Apr-2006 [ ] Elapsed: 0:00:01 [ ] Passed: 1 test (100%) [ ] Failed: 0 tests (0%) [ ] Totals: 1 test, 0 errors, 0 warnings [ ] [-] Testcase Dog - Passed [ ] The word dog appears 7 times