> For the complete documentation index, see [llms.txt](https://trizen.gitbook.io/sidef-lang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trizen.gitbook.io/sidef-lang/programming_tasks/c/count_occurrences_of_a_substring.md).

# Count occurrences of a substring

Built-in:

```ruby
say "the three truths".count("th")
say "ababababab".count("abab")
```

User-created function:

```ruby
func countSubstring(s, ss) {
    var re = Regex(ss.escape, 'g')      # 'g' for global
    var counter = 0
    while (s =~ re) { ++counter }
    return counter
}
 
say countSubstring("the three truths","th")
say countSubstring("ababababab","abab")
```

#### Output:

```
3
2
```
