Having problems with your account or logging in?
A lot of changes are happening in the community right now. Some may affect you. READ MORE HERE

How can I count the occurrence of a word in a string?

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.

e.g.

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


RESULTS:

[ ] 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

Old KB# 21092

DISCLAIMER:

Some content on Community Tips & Information pages is not officially supported by Micro Focus. Please refer to our Terms of Use for more detail.
Top Contributors
Version history
Revision #:
1 of 1
Last update:
‎2013-02-15 19:16
Updated by:
 
The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.