Thursday, 12 December 2013

Count string occurrence in string

This is from a javascript question on StackOverflow.

You just have to see rebolek's answer here to know what we are doing. The function below is the same with minor modifications.

Code:
num-occurrences: func [big-string [string!] search-string [string!]] [
num: 0
parse big-string [some [thru search-string (num: num + 1)]]
return num
]
view raw occurrences hosted with ❤ by GitHub


Usage:
>> num-occurrences "aaa" "aa"
== 1
>> num-occurrences "rebol all night long" "o"
== 2
>> num-occurrences "10: 1 10: 2 10: 3 10: 4" "10"
== 4
view raw usage hosted with ❤ by GitHub


Keep in mind, though that this code will not work when you have case-sensitivity as a concern. Also, repeated strings will be an issue (e.g. In "aaa", you will get 1 occurrence of "aa" instead of 2).

No comments:

Post a Comment