Count occurrences of a substring: Difference between revisions

From Rosetta Code
Content added Content deleted
(started new task)
 
(added perl and python solutions)
Line 9: Line 9:
2
2
</lang>
</lang>

=={{header|Perl}}==
This solution uses regex, hence the substring cannot contain regex metacharacters
<lang perl>sub countSubstring {
my ($str, $sub) = @_;
my $count = () = $str =~ /$sub/g;
return $count;
# or return scalar( () = $str =~ /$sub/g );
}
print countSubstring("the three truths","th"), "\n";
print countSubstring("ababababab","abab"), "\n";
</lang>

=={{header|Python}}==
<lang python>>>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2</lang>

Revision as of 09:41, 16 June 2011

Task
Count occurrences of a substring
You are encouraged to solve this task according to the task description, using any language you may know.

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>

Perl

This solution uses regex, hence the substring cannot contain regex metacharacters <lang perl>sub countSubstring {

 my ($str, $sub) = @_;
 my $count = () = $str =~ /$sub/g;
 return $count;
  1. or return scalar( () = $str =~ /$sub/g );

}

print countSubstring("the three truths","th"), "\n"; print countSubstring("ababababab","abab"), "\n"; </lang>

Python

<lang python>>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2</lang>