| Bytes | Lang | Time | Link |
|---|---|---|---|
| 015 | AWK | 250729T173853Z | xrs |
| 024 | Desmos | 250801T230939Z | ErikDaPa |
| 116 | Pascal | 250716T040008Z | Kai Burg |
| 006 | Juby | 230624T153347Z | Jordan |
| 001 | Thunno 2 | 230624T145023Z | The Thon |
| 016 | Factor | 221017T112837Z | chunes |
| 002 | Vyxal | 221017T111729Z | DialFros |
| 001 | Jelly | 161001T063011Z | Jonathan |
| 060 | Fortran GFortran | 200210T093027Z | DeathInc |
| 004 | Burlesque | 200210T092433Z | DeathInc |
| 016 | Ahead | 200210T064411Z | snail_ |
| 092 | naz | 200210T045854Z | sporebal |
| 004 | W | 191218T142423Z | user8505 |
| 029 | Wren | 191218T141351Z | user8505 |
| 011 | Retina | 191026T031003Z | Sara J |
| 002 | Japt | 191026T012655Z | trillian |
| 015 | Zsh | 191024T144138Z | GammaFun |
| 040 | TSQL | 150902T210409Z | MickyT |
| 001 | 05AB1E | 190919T104404Z | Kevin Cr |
| 001 | APL Dyalog Extended | 190919T093022Z | Adá |
| 002 | Jelly | 170324T100226Z | steenber |
| 055 | C | 170324T084731Z | jdt |
| 052 | Java 7 | 161006T121654Z | Kevin Cr |
| nan | 150907T105820Z | Qwertiy | |
| nan | 161006T155549Z | Chad Bax | |
| 003 | Dyalog APL | 150903T041006Z | Adá |
| 035 | PHP | 150902T102410Z | jrenk |
| 027 | R | 150907T101834Z | David Ar |
| 016 | Perl | 150902T115347Z | manatwor |
| 003 | Pip | 150903T181257Z | DLosc |
| 003 | APL | 150902T180035Z | Alex A. |
| 116 | C++ TemplateMetaprogramming | 150902T181048Z | Otomo |
| 003 | K | 150902T180537Z | kirbyfan |
| 031 | scala | 150903T081436Z | gilad ho |
| 018 | Ruby | 150903T073139Z | Vasu Ada |
| 020 | Ruby | 150902T112212Z | Cristian |
| 030 | ><> Fish | 150902T194316Z | cole |
| 025 | Julia | 150902T175517Z | Alex A. |
| 021 | Julia | 150903T034915Z | Glen O |
| 023 | Element | 150903T020238Z | PhiNotPi |
| 016 | Snowman 1.0.2 | 150903T013844Z | Doorknob |
| 078 | C++ | 150903T011821Z | ex-bart |
| 032 | PowerShell | 150902T133931Z | AdmBorkB |
| 029 | Python 3 | 150902T094843Z | Beta Dec |
| 024 | Labyrinth | 150902T172403Z | Martin E |
| 052 | STATA | 150902T184447Z | bmarks |
| 010 | O | 150902T181721Z | kirbyfan |
| 005 | CJam | 150902T170804Z | Ypnypn |
| 021 | Haskell | 150902T165140Z | Otomo |
| 121 | Batch File | 150902T152647Z | AdmBorkB |
| 005 | J | 150902T152453Z | Martin E |
| 012 | Retina | 150902T152249Z | Martin E |
| 048 | C# | 150902T141804Z | Alex Car |
| 026 | Javascript ES6 | 150902T143030Z | ETHprodu |
| 024 | Bash | 150902T142341Z | manatwor |
| 033 | rs | 150902T140549Z | kirbyfan |
| 026 | Bash + grep | 150902T130401Z | Tarod |
| 003 | Pyth | 150902T123125Z | Maltysen |
| 032 | JavaScript | 150902T094722Z | edc65 |
| 033 | Octave / Matlab | 150902T101144Z | Luis Men |
| 003 | Pyth | 150902T094341Z | izzyg |
Pascal, 116 B
The character to count is entered first, followed by at least one other character.
program p(input,output);var c:0..10;b,n:char;begin
c:=0;read(n,b);repeat read(b);c:=c+ord(b=n)until EOF;write(c)end.
Longified:
program findTheOccurrencesOfACharacterInAnInputString(input, output);
var
{ Writing `0‥10` is shorter than `integer`. }
count: 0‥10;
buffer, needle: char;
begin
count ≔ 0;
read(input, needle, buffer);
{ `Repeat … until …` is shorter than `while … do begin … end`. }
repeat
begin
count ≔ count + ord(buffer = needle);
read(input, buffer)
end
until EOF(input);
writeLn(output, count)
end.
Factor, 16 bytes
[ histogram at ]
Oddly enough, I don't think Factor has a built-in for this. This is two bytes shorter than both
[ '[ _ = ] count ]
and
[ indices length ]
Jelly, 1 byte
ċ
The obvious implementation would be 3 bytes: s1ċ, which splits a string or list (left argument) into slices of length 1 with s1 and counts occurrences of the character (right argument) with ċ.
However, since the character will only ever be of length 1, we could, instead, inspect all non-empty contiguous slices of a string with Ẇ; the character will only ever match those slices that are of length 1.
...and since a string is an array of characters, the function can just be ċ.
Fortran (GFortran), 60 bytes
character a(10),b
read('(10a,a)'),a,b
print*,count(a==b)
end
Takes input as an 11 length string, the last char being b.
Burlesque, 4 bytes
peCN
Takes input as "string" 'i to search string for i.
If special inputs are not allowed:
Burlesque, 6 bytes
pe-]CN
Takes input as two quoted strings.
pe # Parse and evaluate
CN # Count
Ahead, 16 bytes
The first character on stdin is the counted character, and the remainder of stdin is the string.
i&>jlir
@Or+=t<
naz, 92 bytes
2x1v2a2x2v8a2x3v1r2x4v1x1f3r3x2v3e3x4v2e1f0x1x2f1v1a2x1v1f0x1x3f1v3x3v4e1o0x1x4f9s1o1s1o0x1f
Works for any valid input string terminated with the control character STX (U+0002), with the character to search for appearing first (e.g. t, tttggloyoi).
Explanation (with 0x commands removed)
2x1v # Set variable 1 equal to 0
2a2x2v # Set variable 2 equal to 2
8a2x3v # Set variable 3 equal to 10
1r2x4v # Store the first byte of the input string in variable 4
1x1f # Function 1
3r # Read the 3rd byte of input, then remove it from the input
# This has the effect of skipping over the comma and space
3x2v3e # Jump to function 3 if it equals variable 2
3x4v2e # Jump to function 2 if it equals variable 4
1f # Otherwise, jump back to the start of the function
1x2f # Function 2
1v1a2x1v1f # Load variable 1 into the register, add 1,
# and store the new value in variable 1
# Then, jump to function 1
1x3f # Function 3
1v3x3v4e1o # Load variable 1 into the register
# Jump to function 4 if the register equals variable 3
# Otherwise, output once
1x4f # Function 4
9s1o1s1o # Subtract 9 and output, then subtract 1 and output
# (outputs "10")
1f # Call function 1
Wren, 29 bytes
Very hard to golf.
Fn.new{|a,b|a.count{|i|i==b}}
Explanation
Fn.new{|a,b| // Anonymous function with parameters a & b
a.count // Count every item
{|i| // that...
i==b}} // is equal to b
Wren, 36 bytes
Fn.new{|a,b|a.trim(a.trim(b)).count}
Explanation
Fn.new{|a,b| } // Uninteresting anonymous function
a.trim(b) // Remove all occurences of b in a
a.trim( ) // Trim this result with a, keeping the removed occurences
.count // Find the length of this result
Retina, 11 bytes
w`^(.)¶.*\1
Takes input as two lines - the first line is the character, the second is the string.
Could be 10 bytes if taking input as the character preprended to the string, but that felt a bit too cheaty.
Explanation
w`^(.)¶.*\1 # (implicit count stage as there is just one line)
w` # Include overlapping matches for the pattern
(.) # Match a single character...
^ # ...at the start of the input...
¶ # ... and followed by a newline...
.* # ...then zero or more arbitrary characters...
\1 # ...and then the first character again
# (implicitly output the number of matches)
Zsh, 15 bytes
<<<${#1//[!$2]}
Similar to the bash answer, but more compact thanks to Zsh allowing both ${ //} and ${# } in the same expansion.
T-SQL, 99 40 Bytes
SELECT 11-LEN(REPLACE(s,c,'')+'x')FROM t
Simply does a difference between the input string and the string with the character removed. Takes input from table t
Edit changed to remove an issue with counting spaces and to take into account current acceptable inputs for SQL. Thanks @BradC for all the changes and savings
05AB1E, 1 byte
¢
First input is the character, second the string.
Try it online or verify both test cases at once.
Explanation:
¢ # Count the amount of occurrences of the first (implicit) input-character
# in the second (implicit) input-string
# (after which the result is output implicitly)
Jelly, 2 bytes, non-competing
There is a one-byte Jelly solution, but that takes in the argument in a rather particular way. With 1 byte extra, we can just input test instead of ["t", ...]
fL
f filter all elements from the first implicit input that are not in the second implicit input
"onomatopoe" f "o" filters out all non-"o" chars --> oooo
L Get the length of the remainder.
C, 55 bytes
t;c(char* i,char z){t=0;for(;*i;)t+=*i++==z;return t;}
Java 7, 69 68 54 52 bytes
int c(String...a){return a[0].split(a[1]).length-1;}
Surprisingly enough there wasn't a Java answer yet..
14 bytes saved thanks to @Geobits!
If a completely flexible input is allowed, we can save an additional byte by having a String-array parameter (51 bytes):
int c(String[]a){return a[0].split(a[1]).length-1;}
Ungolfed & test code:
class M{
static int c(String... a){
return a[0].split(a[1]).length-1;
}
public static void main(String[] a){
System.out.println(c("tttggloyoi", "t"));
System.out.println(c("onomatopoe", "o"));
}
}
Output:
3
4
Javascript
Program, 48 chars
alert(prompt().match(/(.)(?=.*\1$)|$/g).length-1)
Function with 1 argument (ES6), 39 chars
f=s=>s.match(/(.)(?=.*\1$)|$/g).length-1
Function with 2 arguments (ES6), 28 chars
f=(s,c)=>s.split(c).length-1
I have been outgolfed.
PowerShell, 75 Bytes (Single Run)
nv a (read-host).split(", ");foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|ohThe above will only work once, will error if variables still have values from last run(run twice in same environment).
PowerShell, 82 Bytes (Infinite Use)
$c=0;nv a (read-host).split(", ")-f;foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|ohThe above can be used any number of times in the same environment.
Dyalog APL, 3 bytes
+/=
I.e. "The sum of the equal bytes". E.g.:
f ← +/=
'onomatopoe' f 'o'
4
or just
'onomatopoe'(+/=)'o'
4
K doesn't beat APL this time.
PHP, 36 35 bytes
<?=substr_count($argv[1],$argv[2]);
Usage:
Call the script with two arguments.
php script.php qwertzqwertz q
PHP, 23 bytes
If you register global Variables (only possible in PHP 5.3 and below) you can save 12 bytes (thanks to Martijn)
<?=substr_count($a,$b);
Usage:
Call the script and declare global variables php script.php?a=qwertzqwertz&b=q
R, 27 bytes
sum(strsplit(x,"")[[1]]==y)
Usage
sum(strsplit("tttggloyoi","")[[1]]=="t")
[1] 3
sum(strsplit("onomatopoe","")[[1]]=="o")
[1] 4
Or, Another one with 42 bytes
f<-function(x,y)length(gregexpr(y,x)[[1]])
Usage
f("tttggloyoi", "t")
[1] 3
f("onomatopoe", "o")
[1] 4
Perl, 21 16 characters
(13 characters code + 3 character command line option.)
$_=0+s/$^I//g
Sample run:
bash-4.3$ perl -it -pe '$_=0+s/$^I//g' <<< tttggloyoi
3
bash-4.3$ perl -io -pe '$_=0+s/$^I//g' <<< onomatopoe
4
bash-4.3$ perl -i5 -pe '$_=0+s/$^I//g' <<< 1234
0
Pip, 3 bytes
Joining the 3-byte cavalcade...
bNa
Read as "b in a". a and b are command-line arguments. The N operator, unlike its Python counterpart, doesn't just return a truth value; it returns the count.
APL, 7 3 bytes
+/⍷
This creates a function train. It works by creating a vector of zeros and ones corresponding to the indices at which the character appears in the string (⍷). The vector is then summed (+/).
Saved 4 bytes thanks to kirbyfan64sos and NBZ!
C++ Template-Metaprogramming, 160 154 116 bytes
Just for the giggles.
Thanks to ex-bart for golfing it down!
template<int w,int x,int y,int...s>class A:A<w+(x==y),x,s...>{};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;
Usage: The first char in the template instanciation is the character to search.
Complile with clang -std=c++11 -c -> the result is at the beginning of the error message.
Occurences.cpp:1:66: error: too few template arguments for class template 'A'
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
^
Occurences.cpp:1:66: note: in instantiation of template class 'A<3, 't', '\x00'>' requested here
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
Complile with gcc -std=c++11 -c -> the result is at the bottom of the error message.
Occurences.cpp: In instantiation of ‘const int A<3, 't', '\000'>::a’:
Occurences.cpp:1:64: recursively required from ‘const int A<1, 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:1:64: required from ‘const int A<0, 't', 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:2:62: required from here
Occurences.cpp:1:64: error: wrong number of template arguments (2, should be at least 3)
Search for the A<3, 't', '\000'> and A<3, 't', '\x00'>
154 byte version
template<int w,char x,char y,char...s>class A{static const int a=A<w+(x==y),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;
160 byte version:
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;
K, 3 bytes
+/=
K actually beat APL!!! :D Well, now it's a tie... :/
You can call it like this:
+/=["hello";"l"]
Or assign it to a variable first:
f:+/=
f["hello";"l"]
Also note that this does not work in oK. It does work in the official K2 and K5 interpreters, as well as Kona.
scala, 31 bytes
(x:String,y:Char)=>x.count(y==)
Ruby, 18 bytes
->s,c{p s.count c}
Usage:
->s,c{p s.count c}.call 'tttggloyoi', 't'
->s,c{p s.count c}.call 'onomatopoe', 'o'
Ruby, 22 20 bytes
p gets.count(gets)-1
Demo: http://ideone.com/MEeTd2
The -1 is due to the fact that gets retrieves the input, plus a newline character. Ruby's String#count counts the number of times any character from the argument occurs in the string.
For example, for the input [test\n, t\n], the t occurs twice and the \n occurs once, and needs to be subtracted.
><> (Fish), 30 bytes
0&v
=?\ilb
=?\:@=&+&l1
n&/;
Takes the string, then character to count. Input isn't separated (at least in the online interpreter). Try it on the online interpreter: http://fishlanguage.com I counted the bytes by hand, so let me know if I'm wrong.
Explanation
First off, ><> is 2 dimensional and and loops through a line or column until it hits a ; or error. This means that if it's proceeding left to right (like it does at the beginning of a program), it will wrap around the line if it reaches the end and is not moved or told to stop the program. Some characters per line will be repeated because they have different functions depending on the direction of the pointer, and the fourth line will have characters in reverse order because the pointer moves right to left.
A summary of the program is provided below. Look at the instructions listed for ><> on esolangs to see what each individual character does.
Line 1: 0&v
0&v -put 0 into the register and change direction to down-up
Line 2: =?\ilb
(starting where line 1 moves the pointer to, i.e. the third character)
\ -reflect the pointer and make it move left-right
i -read input
lb=?\ -reflect downwards if there are 11 values in the stack
line 3: =?\:@=&+&l1
(starting at the third character)
:@ -duplicate y and shift the stack e.g. ['x','y','y'] -> ['y','x','y']
=&+& -increment the register if the character popped from x = y
l1=?\ -reflect downwards if there is 1 value in the stack
Line 4: n&/;
(starting at the third character)
/ -reflect right-left
&n; -print value of the register
Julia, 26 25 bytes
f(s,c)=endof(findin(s,c))
The findin function returns the indices in the first argument at which the second argument is found as a vector. The length of the vector is the number of occurrences.
Saved one byte thanks to Glen O.
Julia, 21 bytes
f(s,c)=sum(i->c==i,s)
Note that it requires that c be a char, not a single-character string. So you use it as f("test me",'e') (which returns 2) and not f("test me","e") (which returns 0, because 'e'!="e").
Element, 23 bytes
__);11'[)\
~="0 1@][+]`
The newline is part of the program. I am actually using it as a variable name.
This program basically works by storing the target character in a variable, keeping the current string on the top of the stack, and then looping the "chop, compare, and move result underneath" process, adding up the results in the end.
The newline as a variable name comes from using the newline at the end of input by chopping it off and storing into it. The newline in the code is where I read from it.
Input is like this:
qqqqwwweee
q
Output is like this
4
Snowman 1.0.2, 16 characters
~vgvgaSaLNdEtSsP
Surprisingly short. Explanation:
~ make all vars active (even though we only need two, we don't really care)
vgvg get two lines of input
aS split first line on second line
aL length of the new array
NdE decrement (because ex. "axbxc""x"aS -> ["a" "b" "c"] which is length 3)
tSsP to-string and print
C++, 78 bytes
int main(int,char**v){int c=0,i=0;while(i<10)v[1][i++]==*v[2]&&++c;return c;}
Call like this:
$ g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out tttggloyoi t; echo $?
3
PowerShell, 32 Bytes
A four-for-one! And they're all the same length! :)
($args[0]-split$args[1]).Count-1
or
param($a,$b)($a-split$b).Count-1
Alternatively,
$args[0].Split($args[1]).Count-1
or
param($a,$b)$a.Split($b).Count-1
The first two styles use the inline operator -split, while the second two implicitly casts the first argument as a String and uses the .Split() string-based operator. In all instances an array is returned, where we must decrement Count by one, since we're getting back one more array item than occurrences of the second argument.
This one was kinda fun...
Python 3, 29 bytes
print(input().count(input()))
Meh, this was easy. Assumes that input is a ten letter string.
Labyrinth, 32 29 27 24 bytes
),}{)-
@ , +);__
!-`{:}
This reads the single character first, followed by the string in which to count, and assumes that there are no null-bytes in the string.
Explanation
The code starts with ),}, which sets the bottom of the stack to 1, reads the first character and moves it to the auxiliary stack for future use. The 1 will be our counter (the offset of 1 will be cancelled later and is necessary for the IP to take the required turns).
The IP will now move down to read the first character of the search string with ,. The value is negated with `, again to get the correct turning behaviour. While we're reading characters from STDIN, the IP will now follow this loop:
}{)-
, +);__
`{:}
{:} makes a copy of the stored character code and + adds it to the current value. If the result is 0 (i.e. the current character is the one we're looking for), the IP moves straight ahead: - simply gets rid of the 0, ) increments the counter, {} is a no-op.
However, if the result after + is non-zero, we don't want to count the current character. So the IP takes a right-turn instead. That's a dead-end, so that code there is executed twice, once forwards and once backwards. That is, the actual code in this case becomes );___;)+-){}. ); just gets rid of that non-zero difference, ___ pushes 3 zeroes, but ; discards one of them. ) increments one of the two remaining two zeroes, + adds them into a single 1, - subtracts it from the counter and ) increments the counter. In other words, we've created a very elaborate no-op.
When we hit EOF, , pushes -1, which ` turns into 1 and the IP takes a right-turn. - subtracts the 1 from the counter (cancelling the initial offset). ! prints the counter and @ terminates the program.
STATA, 52 bytes
di _r(a)_r(b)
di 10-length(subinstr("$a","$b","",.))
Gets the two strings as inputs. Replaces all occurrences of the second string (the character) with empty string. Subtract that from 10, since the length of the first string is 10.
Unfortunately functions in STATA can't be shortened the same way that variable names and commands can. Also, this doesn't work in the online interpreter, since it doesn't include these functions.
O, 23 10 bytes
ie\i-e@-_p
Original:
0K;i""/iJ;l{J=K+:K;}dKp
I don't think I can get this any shorter... :/
Ah, I'm stupid. I forgot the traditional method of counting occurrences: subtract the string lengths.
CJam, 5 bytes
ll/,(
Explanation
l e# read x
l e# read y
/ e# split x by y
, e# count
( e# subtract one
Haskell, 21 bytes
a!b=sum[1|x<-a,x==b]
Batch File, 121 Bytes
Because I'm a masochist ...
SET c=0
SET e=_
SET t=%1%%e%
:l
SET a=%t:~0,1%
IF "%a%"=="%2" SET /A c+=1
SET t=%t:~1%
IF NOT "%t%"=="%e%" GOTO l
ECHO %c%
Warning: Assumes that _ doesn't occur in the input string. If it does, then the variable e needs to be adjusted appropriately.
This sets up our counter variable, c, and our end-of-string demarcation as _, before appending that to our input string %1 and setting the concatenated string to t. Then, we're entering loop :l, we set a temporary character variable a to be the first character of t, check if it matches our second input string %2 and increment c if true, then trim the first character off of t. Our end-of-loop condition checks t against our end-of-string demarcation, and loops back if not. We then echo out the value of our counter.
It would probably be possible to use a FOR loop instead, but that would necessitate enabling DelayedExpansion, which I think will actually be longer byte-wise than this. Verification of that is left as an exercise to the reader.
J, 5 bytes
+/@:=
I feel like J would have a built-in for this, but I haven't been able to find one - maybe one of the active J users can enlighten me. So instead this first applies = to the inputs, turning each character into 1 if it's equal to the requested one or 0 otherwise. Then +/ computes the sum of that list.
Retina, 12 bytes
(.)(?=.*\1$)
Simply a regex which matches a character which is equal to the last character in the input (except itself). When given a single regex, Retina simply returns the number of matches.
C#, 36 51 48
Debug.Write(args[0].split(args[1][0]).Length-1);
Javascript (ES6), 26 bytes
(a,b)=>a.split(b).length-1
This quick'n'easy solution defines an anonymous function. To use it, add a variable declaration to the beginning. Try it out:
z=(a,b)=>(a.split(b)||[0]).length-1;
input1=document.getElementById("input1");
input2=document.getElementById("input2");
p=document.getElementById("a");
q=function(){
setTimeout(function(){
p.innerHTML=z(input1.value,input2.value)||0;
},10);
};
input1.addEventListener("keydown",q);
input2.addEventListener("keydown",q);
<form>Text to search: <input type="text" id="input1" value="hello world!"/><br>Char to find: <input type="text" id="input2" value="l"/></form>
<h3>Output:</h3>
<p id="a">3</p>
EDIT: Oh, I see there's a very similar solution already. I hope that's OK.
Bash, 24 characters
x=${1//[^$2]}
echo ${#x}
Sample run:
bash-4.3$ bash letter-count.sh tttggloyoi t
3
bash-4.3$ bash letter-count.sh onomatopoe o
4
rs, 33 bytes
+(.)(.* (?!\1).)/\2
(.*)../(^^\1)
This is pretty simple. The first line removes all characters except the ones we're counting. The next line counts the number of characters that are left, excluding the one we're searching for.
Takes input separated by spaces, e.g.:
onomatopoe o
Bash + grep, 26 bytes
grep -o "$1"<<<"$2"|wc -l
Pyth - 3 bytes
A different, less obvious, Pyth answer of the same size. It folds counting over the input.
/FQ
JavaScript, 32
(p=prompt)().split(p()).length-1
Octave / Matlab, 33 bytes
sum(input('','s')==input('','s'))
Pyth, 3 bytes
/ww
Example run:
$ pyth -c '/ww'
sdhkfhjkkj
k
3
Of course, the user could input more or less than 10 letters on the first input, but we don't need to worry about what happens when the user violates the spec.