Count occurrences of a substring: Difference between revisions
Added D version |
added Fortran |
||
Line 101: | Line 101: | ||
<pre>3 |
<pre>3 |
||
2</pre> |
2</pre> |
||
=={{header|Fortran}}== |
|||
{{works with|Fortran|90 and later}} |
|||
<lang fortran>program Example |
|||
implicit none |
|||
integer :: n |
|||
n = countsubstring("the three truths", "th") |
|||
write(*,*) n |
|||
n = countsubstring("ababababab", "abab") |
|||
write(*,*) n |
|||
n = countsubstring("abaabba*bbaba*bbab", "a*b") |
|||
write(*,*) n |
|||
contains |
|||
function countsubstring(s1, s2) result(c) |
|||
character(*), intent(in) :: s1, s2 |
|||
integer :: c, p, posn |
|||
c = 0 |
|||
if(len(s2) == 0) return |
|||
p = 1 |
|||
do |
|||
posn = index(s1(p:), s2) |
|||
if(posn == 0) return |
|||
c = c + 1 |
|||
p = p + posn + len(s2) |
|||
end do |
|||
end function |
|||
end program</lang> |
|||
Output |
|||
<pre>3 |
|||
2 |
|||
2</pre> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
Revision as of 07:07, 17 June 2011
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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>
The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
ALGOL 68
Algol68 has no build in function to do this task, hence the next to create a count string in string routine. <lang algol68>#!/usr/local/bin/a68g --script #
PROC count string in string = (STRING needle, haystack)INT: (
INT start:=LWB haystack, next, out:=0; FOR count WHILE string in string(needle, next, haystack[start:]) DO start+:=next+UPB needle-LWB needle; out:=count OD; out
);
printf(($d" "$,
count string in string("th", "the three truths"), # expect 3 # count string in string("abab", "ababababab"), # expect 2 # count string in string("a*b", "abaabba*bbaba*bbab"), # expect 2 # $l$
))</lang> Output:
3 2 2
C
<lang C>#include <stdio.h>
- include <string.h>
int match(char *s, char *p, int overlap) {
int c = 0, l = strlen(p);
while (*s != '\0') { if (strncmp(s++, p, l)) continue; if (!overlap) s += l - 1; c++; } return c;
}
int main() {
printf("%d\n", match("the three truths", "th", 0)); printf("overlap:%d\n", match("abababababa", "aba", 1)); printf("not: %d\n", match("abababababa", "aba", 0)); return 0;
}</lang>
C++
<lang cpp>#include <iostream>
- include <string>
// returns count of non-overlapping occurrences of 'sub' in 'str' int countSubstring(const std::string& str, const std::string& sub) {
if (sub.length() == 0) return 0; int count = 0; for (size_t offset = 0; (offset < str.length()) && ((offset = str.find(sub, offset)) != std::string::npos); offset += sub.length()) { ++count; } return count;
}
int main() {
std::cout << countSubstring("the three truths", "th") << '\n'; std::cout << countSubstring("ababababab", "abab") << '\n'; std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';
}</lang> Output:
3 2 2
D
<lang d>import std.stdio, std.algorithm;
void main() {
writeln("the three truths".count("th")); writeln("ababababab".count("abab"));
}</lang> Output:
3 2
Fortran
<lang fortran>program Example
implicit none integer :: n n = countsubstring("the three truths", "th") write(*,*) n n = countsubstring("ababababab", "abab") write(*,*) n n = countsubstring("abaabba*bbaba*bbab", "a*b") write(*,*) n
contains
function countsubstring(s1, s2) result(c)
character(*), intent(in) :: s1, s2 integer :: c, p, posn c = 0 if(len(s2) == 0) return p = 1 do posn = index(s1(p:), s2) if(posn == 0) return c = c + 1 p = p + posn + len(s2) end do
end function end program</lang> Output
3 2 2
Java
This method removes the first occurrence of the substring, checks for changes, and continues if something changed. It counts each removal attempt (even if nothing is replaced), so the count starts at -1 to offset the last removal attempt where nothing changed. <lang java>import java.util.regex.Pattern;
public class CountSubstring { public static int countSubstring(String subStr, String str){ int ans = -1;//start at -1 since we always count at least 1 replacement String newStr = str; do{ str = newStr; newStr = str.replaceFirst(Pattern.quote(subStr), "");//attempt a removal ans++;//count it }while(!str.equals(newStr)); return ans; }
public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }</lang> Output:
3 2 2
Perl
<lang perl>sub countSubstring {
my $str = shift; my $sub = quotemeta(shift); 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>
Perl 6
<lang perl6>sub count-substring($big,$little) { +$big.comb: /$little/ }
say count-substring("the three truths","th"); say count-substring("ababababab","abab");</lang> Note that in Perl 6 the /$little/ matches the variable literally, so there's no need to quote regex metacharacters. Also, prefix + forces numeric context in Perl 6 (it's a no-op in Perl 5). One other style point: we now tend to prefer hyphenated names over camelCase.
PureBasic
<lang PureBasic>a = CountString("the three truths","th") b = CountString("ababababab","abab")
- a = 3
- b = 2</lang>
Python
<lang python>>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2</lang>
Tcl
The regular expression engine is ideal for this task, especially as the ***= 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"] puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]</lang>
Output:
3 2 2