| Bytes | Lang | Time | Link |
|---|---|---|---|
| 210 | Pascal | 250314T080045Z | Kai Burg |
| 006 | K/Kona | 140613T174929Z | Kyle Kan |
| 025 | Cobra | 140613T112711Z | Οurous |
| 022 | Python 2.x | 140610T160349Z | seequ |
| 038 | Java | 140612T013548Z | Ypnypn |
| 225 | C++ | 140611T201310Z | bacchusb |
| 023 | Mathematica | 140610T172750Z | DavidC |
| 101 | Fortran 90 | 140611T171858Z | Kyle Kan |
| 048 | Lua | 140611T141331Z | Teun Pro |
| 113 | Delphi XE3 | 140611T135109Z | Teun Pro |
| 120 | C | 140611T114327Z | aragaer |
| 066 | C# 66 Bytes | 140611T075615Z | tsavinho |
| 073 | C# | 140611T004823Z | mnsr |
| 106 | Applescript | 140610T181254Z | Digital |
| 007 | J | 140610T172953Z | ɐɔıʇǝɥʇu |
| 032 | Powershell | 140610T171359Z | DarkAjax |
| 032 | JavaScript | 140610T165645Z | Michael |
| 003 | GolfScript | 140610T170411Z | Dennis |
Pascal, 210 B
In Standard Pascal a string has necessarily a minimum length of two char values.†
Therefore it is not possible to find the count of occurrences of a “string” of length one in another string.
type c=char;z=integer;function f(s:array[m..n:z]of c;t:array[p..q:z]of c):z;var
i,j,a,r:z;begin r:=0;i:=n-q+p;for i:=m to i do begin a:=1;for j:=0 to q-p do
begin a:=a*ord(s[i+j]=t[p+j])end;r:=r+a end;f:=r end;
Antighoulfed:
function occurrencesCount(
{ In Pascal a string is a `packed array[1‥N] of char`, N ≥ 2. }
sample: packed array[sampleFirst‥sampleLast: integer] of char;
needle: packed array[needleFirst‥needleLast: integer] of char
): integer;
var
sampleIndex, needleOffset, intermediateResult, result: integer;
begin
result ≔ 0;
sampleIndex ≔ sampleLast − needleLast + needleFirst;
for sampleIndex ≔ sampleFirst to sampleIndex do
begin
intermediateResult ≔ 1;
for needleOffset ≔ 0 to needleLast − needleFirst do
begin
{ The product is zero if any factor is zero. }
intermediateResult ≔ intermediateResult *
ord(
sample[sampleIndex + needleOffset]
=
needle[needleFirst + needleOffset]
)
end;
result ≔ result + intermediateResult
end;
{ In Pascal the function’s result is defined by assigning a value
to the implicitly declared variable bearing the function’s name. }
occurrencesCount ≔ result
end;
† Extended Pascal allows an empty string (''), too.
K/Kona 6
+/y~'x
where x is the string and y the substring. ~ is the negate operator, with ', it is applied to every element in x; it will return 0 if it does not match and 1 if it does match. Since it is applied element-wise, the result of y~'x is a vector, the +/ then sums the result giving the total number of occurrences.
Unfortunately, this method requires that y is only one character, otherwise we will be comparing a multi-character string to a single character string, resulting in a length error.
Cobra - 25
print a.split(b).length-1
Python 2.x - 49 23 22 bytes
This is assuming variable input is okay. Both strings can be of any length.
Shortened @avall.
a='s'
b='aaaabbbbsssffhd'
print~-len(b.split(a))
49 bytes version, counts every instance of the substring ('aba' is in 'ababa' twice).
a='s'
b='aaaabbbbsssffhd'
print sum(a==b[i:i+len(a)]for i in range(len(b)))
Java (38)
System.out.print(a.split(b).length-1);
(The question did not require a complete program or function.)
C++ 225
int n,k,m;
int main()
{
string s1,s2;
cin>>s1;
cin>>s2;
int x=s1.size(),y=s2.size();
if(x>=y)
{
for(int i=0;i<x;i++)
{
k=0,m=0;
for(int j=0;j<y;j++)
{
if(s2[j]==s1[i+m])
{
k++,m++;
}
else break;
}
if(k==y)
{
n++;
i+=(y-1);
}
}
}
cout<<n<<endl;
return 0;
}
Mathematica 26 23
Works like Dennis' algorithm, but wordier:
Length@StringCases[a,b]
Three chars shaved off by Szabolics.
Fortran 90: 101
Standard abuse of implicit typing, works for any length arrays a and b, though one should expect that len(a) < len(b).
function i();i=0;k=len(trim(b))-1;do j=1,len(trim(a))-k;if(a(j:j+k)==b(1:1+k))i=i+1;enddo;endfunction
This function must be contained within a full program to work. a and b are received from stdin and can be entered either on the same line (either comma or space separated) or on different lines. Compile via gfortran -o main main.f90 and execute as you would any other compiled program.
program main
character(len=256)::a,b
read*,a,b
print*,i()
contains
function i()
i=0
k=len(trim(b))-1
do j=1,len(trim(a))-k
if(a(j:j+k)==b(1:1+k))i=i+1
end do
end function
end program main
Tests:
>ababa aba
2
I could make the above return 1 if I add 4 characters (,k+1) for the do loop
> aaaabbbbbsssffhd s
3
Lua (48)
So i thought I could just submit another answer, this time in lua. Its very possible this could be improved a lot, im very new to this.
print((a.len(a)-a.len(a.gsub(a,b,"")))/b.len(b))
Delphi XE3 (113)
Takes 2 strings, removes substring from string and substracts new length from old length followed by a division of the substring length.
function c(a,b:string):integer;begin c:=(Length(a)-Length(StringReplace(a,b,'',[rfReplaceAll])))div Length(b)end;
Testing:
c('aaaabbbbsssffhd','s') = 3
c('aaaabbbbsssffhd','a') = 4
c('ababa','aba') = 1
c('ababa','c') = 0
C 130 120
Note: will probably crash if called with incorrect arguments.
r;main(int c,char**a){char*p=*++a,*q,*t;while(*p){for(q=a[1],t=p;*q&&*q==*t;q++)t++;*q?p++:(p=t,r++);}printf("%d\n",r);}
Ungolfed (kinda):
int main(int argc, char *argv[]) {
int result = 0;
char *ptr = argv[1];
while (*ptr) {
char *tmp, *tmp2 = ptr;
// str(n)cmp
for (tmp = argv[2]; *tmp; tmp++, tmp2++)
if (*tmp != *tmp2)
break;
if (*tmp) {
ptr++;
} else {
result++;
ptr += tmp;
}
}
printf("%d\n", result);
}
Old version with strstr and strlen: 103
l;main(int c,char**a){char*p=a[1];l=strlen(a[2]);while(c++,p>l)p=strstr(p,a[2])+l;printf("%d\n",c-5);}
C# - 66 Bytes
//s = "aba"
//t = "ababa"
Console.Write(t.Split(new[]{s},StringSplitOptions.None).Length-1);
//Output: 1
C# - 73
//a = "aba";
//b = "ababa";
Console.Write(b.Split(new string[]{a},StringSplitOptions.None).Length-1);
// output = "1"
Applescript, 106 bytes
Applescript is a fun, but silly language to golf in.
on run a
set AppleScript's text item delimiters to (a's item 1)
(count of (a's item 2)'s text items)-1
end
Run with osascript:
$ osascript instr.scpt s aaaabbbbsssffhd
3
$
J (7)
No use of external libraries Check! , or your language's API. Check...? I don't know what an language API is. You have to implement it manually Check!
No file I/O Check!
No connecting with a server, website, et cetera Check!
+/a E.b
How it works:
E. is WindowedMatch: the J Refsheet gives 're' E. 'reread' as example. This gives 1 0 1 0 0 0. Then, the only thing left to do is simply adding this with +/ (basically sum).
I don't think this counts as using your language's built-in function or method for counting occurences, but that's disputable.
EDIT: Just to be clear:
+/'aba'E.'ababa'
2
Powershell 32
($args[0]-split$args[1]).count-1
Works like this:
PS C:\MyFolder> .\ocurrences.ps1 ababa aba
1
Explanation: Uses -split to separate the first argument by the second one, returns the size of the array resulting from the split (minus 1)
JavaScript 32
Nothing really interesting here...
(p=prompt)().split(p()).length-1
split main purpose is to create an array from a string using the delimiter in argument.
GolfScript, 3 bytes
/,(
Assumes string and substring are on the stack.
How it works
/ # Split the string around occurrences of the substring.
, # Get the length of the split array.
( # Subtract 1.