Count occurrences of a substring: Difference between revisions

Content deleted Content added
added perl and python solutions
→‎Tcl: Added implementation
Line 2:
The task is to either create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments: the first argument being the string to search and the second a substring to be search for. It should return an integer count.
 
<lang pseudocode> print countSubstring("the three truths","th")
3
 
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2</lang>
2
</lang>
 
=={{header|Perl}}==
Line 20 ⟶ 19:
print countSubstring("the three truths","th"), "\n";
print countSubstring("ababababab","abab"), "\n";</lang>
</lang>
 
=={{header|Python}}==
Line 28 ⟶ 26:
>>> "ababababab".count("abab")
2</lang>
 
=={{header|Tcl}}==
The regular expression engine is ideal for matching this, especially as the <tt>***=</tt> prefix makes it interpret the rest of the argument as a literal string to match:
<lang tcl>proc countSubstrings {haystack needle} {
regexp -all ***=$needle $haystack
}
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "ababababab" "abab"]</lang>
Output:<pre>3
2</pre>