Find the occurrences of a character in an input string

18

1

Challenge

Write a program that, given a string x which is 10 characters long and a character y, outputs the number of times character y occurs in string x.

The shortest program in bytes to do so wins.

Example

Input: tttggloyoi, t
Output: 3

Input: onomatopoe, o
Output: 4

rosslyn taghoy

Posted 2015-09-02T09:35:11.130

Reputation: 197

11This seems almost too easy of a challenge. Also why limit the input to 10, instead of no limit at all? – Fatalize – 2015-09-02T09:37:28.613

7Needs a winning condition. – isaacg – 2015-09-02T09:41:20.753

2Feel free to rollback my edit if it doesn't agree with you – Beta Decay – 2015-09-02T10:13:23.977

8How flexible is the input format? Can we choose a different delimiter, like a space or newline? Can the string be in quotes? Can we take the letter first and the string second? Will the characters always be lower case letters? If not, which other characters can occur? – Martin Ender – 2015-09-02T10:50:41.923

1@DigitalTrauma I think the OP posted the question and just took off, so if we have any questions, we're probably going to edit in the answers – Beta Decay – 2015-09-02T18:54:36.620

@BetaDecay fair enough - I only just looked at your edit - you made substantial quality improvements. – Digital Trauma – 2015-09-02T18:59:25.637

1The OP didn't specify that functions are allowed. He just said write a program. – mbomb007 – 2015-09-02T19:56:21.670

5This looks suspiciously like a C interview question... – Quentin – 2015-09-02T20:33:36.303

Also posted on GeeksforGeeks Q&A: Create a program that asks the user to input 10 letters..

– manatwork – 2015-09-03T07:37:34.753

@manatwork Good find. This question might be a problem if content on that site is under a restrictive license. – Alex A. – 2015-09-03T16:20:58.230

1@Quentin Let's hope they were smart enough to use the shortest solution in their interview. ;) – ThisSuitIsBlackNot – 2015-09-03T19:35:35.430

Answers

18

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.

isaacg

Posted 2015-09-02T09:35:11.130

Reputation: 39 268

seems like that's not valid pyth anymore? – Ven – 2016-02-09T15:34:03.623

explanation please? – MilkyWay90 – 2019-10-12T15:00:39.223

@MilkyWay90 Here's how you might use this: Try it online!. / just counts the number of occurences in the first input string of the second input string. w takes a line of input.

– isaacg – 2019-10-15T21:28:59.353

@isaacg oh, I see. Thank you! – MilkyWay90 – 2019-10-16T01:52:47.953

11

Pyth - 3 bytes

A different, less obvious, Pyth answer of the same size. It folds counting over the input.

/FQ

Test Suite.

Maltysen

Posted 2015-09-02T09:35:11.130

Reputation: 25 023

7

JavaScript, 32

(p=prompt)().split(p()).length-1

edc65

Posted 2015-09-02T09:35:11.130

Reputation: 31 086

7

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

manatwork

Posted 2015-09-02T09:35:11.130

Reputation: 17 865

6

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.

Martin Ender

Posted 2015-09-02T09:35:11.130

Reputation: 184 808

Wow, I'm over here trying to do all sorts of fancy stuff with rs, and you beat me with lookaheads. +1

– kirbyfan64sos – 2015-09-02T17:47:48.630

4

Python 3, 29 bytes

print(input().count(input()))

Meh, this was easy. Assumes that input is a ten letter string.

Beta Decay

Posted 2015-09-02T09:35:11.130

Reputation: 21 478

4You copied me! :D – isaacg – 2015-09-02T09:54:45.323

1@isaacg Great minds think alike? ;D – Beta Decay – 2015-09-02T09:55:35.640

If you don't need to read input, wouldn't f=lambda x,y:x.count(y) be shorter? (Sorry if this doesn't work, I'm on mobile and can't check) – cole – 2015-09-02T19:46:15.097

@mbomb007 My mistake, thanks for clarifying. – cole – 2015-09-02T19:57:15.003

1Removing the brackets around print saves you a character print input().count(input()) or a,b=input();print a.count(b) with the same amount – Willem – 2015-09-02T19:58:27.303

@willem That assumes that the input is surrounded by speech marks... I don't currently know the acceptability of this – Beta Decay – 2015-09-02T20:01:19.457

well the first one works, sorry edited the comment :-) – Willem – 2015-09-02T20:02:03.183

@willem It's the same thing with the speech marks :P – Beta Decay – 2015-09-02T20:02:46.817

Alright, removing the brackets only works in python 2, and yes you're right about the quote marks, but I needed them in python 2 anyway. Also I saw some debate about that in the comments, so thought it was acceptable. Heres a +1 – Willem – 2015-09-02T20:07:37.413

@undergroundmonorail Remembered it wrong, but still, the OP specified a program. – mbomb007 – 2015-09-03T02:55:33.353

4

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.

Martin Ender

Posted 2015-09-02T09:35:11.130

Reputation: 184 808

4

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;

Otomo

Posted 2015-09-02T09:35:11.130

Reputation: 181

You can shorten ((x==y)?1:0) to just (x==y) to save about 6 bytes (I think). – kirbyfan64sos – 2015-09-02T21:11:15.460

Thanks--wanted to be sure that it is defined behaviour, because I wasn't sure what the standard said about bool to int conversion. – Otomo – 2015-09-02T21:34:05.587

It's defined behavior. – kirbyfan64sos – 2015-09-02T21:34:56.780

Yep, now I know that, too. :) Thank you very much. (I thought maybe it would be implementation dependent.) – Otomo – 2015-09-02T21:37:49.620

1128 bytes: Use anonymous enum instead of static const. Use 0 instead of '\0' to terminate. Use int instead of char. Use a slightly different declaration to instanciate. Remove superflouos newline. template<int w,int x,int y,int...s>class A{enum{a=A<w+(x==y),x,s...>::a};};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;. Checked with g++ and clang. – ex-bart – 2015-09-03T00:17:04.897

Nice, thanks - will change that – Otomo – 2015-09-03T05:33:27.460

Uh, my previous example was actually 127 bytes. I did't notice that my editor appended a newline at the end when saving. – ex-bart – 2015-09-03T11:48:25.483

Anyway, I found another version with 116 bytes, by doing the recursion to a base class. That allows to keep everything in the template parameters: 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;. Live example.

– ex-bart – 2015-09-03T11:55:21.303

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

Doorknob

Posted 2015-09-02T09:35:11.130

Reputation: 68 138

Nice work! I wouldn't have thought that a solution that short would be possible in Snowman. – Alex A. – 2015-09-03T01:40:20.193

3

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

jrenk

Posted 2015-09-02T09:35:11.130

Reputation: 451

1You can remove a space after the comma to get one byte less – Voitcus – 2015-09-02T11:38:07.863

1If you have register globals you can do script.php?a=qwertzqwertz&b=q, and do <?=substr_count($a,$b);, 23 chars – Martijn – 2015-09-02T14:04:30.410

@Martijn good idea thank you! – jrenk – 2015-09-02T14:16:44.873

3

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

manatwork

Posted 2015-09-02T09:35:11.130

Reputation: 17 865

Neat trick with <>! – ThisSuitIsBlackNot – 2015-09-02T16:28:36.630

You could save a byte by dropping -l and ensuring that your input has no trailing newline: echo -en 'onomatopoe\no' | perl -pe '$_=eval"y/".<>."//"' – ThisSuitIsBlackNot – 2015-09-02T16:30:43.543

1And you can knock your total down to 16 with perl -pe '$_+=s/${\<>}//g' – ThisSuitIsBlackNot – 2015-09-02T17:03:03.097

That referencing trick is incredible. Thank you, @ThisSuitIsBlackNot. – manatwork – 2015-09-02T18:42:19.987

Why is the += needed? = seems to work just as well (and should still work when the input happens to start with some digits). – ex-bart – 2015-09-03T15:39:49.037

@ex-bart, to get a nice round zero if the character is no found in the string. – manatwork – 2015-09-03T16:16:17.903

@ex-bart Nice work, you found an edge case! echo -en '1234\n0' | perl -pe '$_+=s/${\<>}//g' gives 1234. Fix for a cost of 1 byte with perl -pe '$_=0+s/${\<>}//g' – ThisSuitIsBlackNot – 2015-09-03T19:28:29.663

@ex-bart Although that brings up another point...if the search character can be a special character like . or *, it needs to be escaped: perl -pe '$_=0+s/\Q${\<>}//g'. 19 bytes total (just one less than manatwork's original solution!) – ThisSuitIsBlackNot – 2015-09-04T02:07:37.877

Using the -i options to put in the second argument makes this shorter. echo -en 'tttggloyoi' | perl -it -pe '$_+=s/$^I//g' is 12 characters +1 for the -i which is a score of 13. – hmatt1 – 2015-09-04T21:28:23.477

Great trick @chilemagic. But the count would be 15, because only -e is for free, everything else gets counted: -i is 2 + p is 1. – manatwork – 2015-09-05T17:55:30.573

3

Bash + grep, 26 bytes

grep -o "$1"<<<"$2"|wc -l

Tarod

Posted 2015-09-02T09:35:11.130

Reputation: 181

3

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.

ETHproductions

Posted 2015-09-02T09:35:11.130

Reputation: 47 880

3

Haskell, 21 bytes

a!b=sum[1|x<-a,x==b]

Otomo

Posted 2015-09-02T09:35:11.130

Reputation: 181

3

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.

Alex A.

Posted 2015-09-02T09:35:11.130

Reputation: 23 761

endof will save you a byte in place of length. – Glen O – 2015-09-03T03:46:07.910

3

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!

Alex A.

Posted 2015-09-02T09:35:11.130

Reputation: 23 761

Is APL curried like K? I would think you could just do something like +/⍷ then (I don't know APL, so I might be wrong). – kirbyfan64sos – 2015-09-02T21:10:20.400

@kirbyfan64sos The only curry I know is food so I'm not sure. But I'll look into it. Thanks for the suggestion! – Alex A. – 2015-09-03T00:12:52.483

@kirbyfan64sos Yes, it is called a function train, so +/⍷ would indeed work, but since we are looking for a single char, one might as well use = instead of ⍷. – Adám – 2015-09-03T07:29:36.327

3

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

MickyT

Posted 2015-09-02T09:35:11.130

Reputation: 11 735

You shouldn't need all the scaffolding, just do SELECT LEN(s)-LEN(REPLACE(s,c,''))FROM t, where t is a pre-populated input table with fields s and c.

– BradC – 2019-10-10T18:54:18.603

On another note, this code gives the wrong answer for strings like A B C D that end in spaces (if you're asked to count spaces), since LEN ignores trailing spaces. – BradC – 2019-10-10T18:59:21.750

@BradC I think way back then, the rules around what was acceptable, especially around SQL was restrictive and unclear. I'll have a look at fixing the space issue when I have a little time – MickyT – 2019-10-10T21:17:26.927

I usually just pad the end and subtract one; in this case input is guaranteed to be exactly 10 characters, you could just hard code it as SELECT 11-LEN(REPLACE(s,c,'')+'x')FROM t – BradC – 2019-10-10T21:30:47.043

@BradC yeah, looking at this again, not sure why I allowed for variable length. Making changes. – MickyT – 2019-10-10T21:37:10.060

3

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

ex-bart

Posted 2015-09-02T09:35:11.130

Reputation: 131

3

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

PhiNotPi

Posted 2015-09-02T09:35:11.130

Reputation: 26 739

3

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.

Try it online.

Adám

Posted 2015-09-02T09:35:11.130

Reputation: 37 779

Please don't edit dozens of posts at once. You're completely flooding the front page. If there are many posts that need editing (which occasionally does happen, e.g. because a new tag is added), then it's generally nice to only do 3 of them at a time and then wait at least 12 hours so they can drop off the front page. – Martin Ender – 2016-05-26T13:46:11.663

@MartinBüttner Yeah, I didn't realize at the time. :-( Regular users do not have the "Minor edit" option... I do realize why it cannot be available for everyone. – Adám – 2016-05-26T14:13:23.757

Unfortunately, there is no such option at all, not even for moderators. – Martin Ender – 2016-05-26T14:19:45.063

2

Japt, 2 bytes

èV

Try it online!

randomdude999

Posted 2015-09-02T09:35:11.130

Reputation: 789

2

Octave / Matlab, 33 bytes

sum(input('','s')==input('','s'))

Luis Mendo

Posted 2015-09-02T09:35:11.130

Reputation: 87 464

2

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.

Cristian Lupascu

Posted 2015-09-02T09:35:11.130

Reputation: 8 369

You can remove $><< and reduce 4 bytes. – Vasu Adari – 2015-09-02T14:33:56.420

@VasuAdari but I need to print the result somehow... – Cristian Lupascu – 2015-09-02T15:13:45.650

can you not do this? -> p gets.count(gets)-1 – Vasu Adari – 2015-09-03T04:34:53.047

@VasuAdari You're right; for the moment I thought that would put qutoes around the output, but it's numeric so it's OK. Thanks! – Cristian Lupascu – 2015-09-03T06:14:30.923

2

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...

AdmBorkBork

Posted 2015-09-02T09:35:11.130

Reputation: 41 581

2

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.

Martin Ender

Posted 2015-09-02T09:35:11.130

Reputation: 184 808

2

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.

AdmBorkBork

Posted 2015-09-02T09:35:11.130

Reputation: 41 581

2

CJam, 5 bytes

ll/,(

Explanation

l      e# read x
 l     e# read y
  /    e# split x by y
   ,   e# count
    (  e# subtract one

Ypnypn

Posted 2015-09-02T09:35:11.130

Reputation: 10 485

2

><> (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

cole

Posted 2015-09-02T09:35:11.130

Reputation: 3 526

2

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").

Glen O

Posted 2015-09-02T09:35:11.130

Reputation: 2 548

2

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'

Vasu Adari

Posted 2015-09-02T09:35:11.130

Reputation: 941

1

Adám

Posted 2015-09-02T09:35:11.130

Reputation: 37 779

1

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)

Kevin Cruijssen

Posted 2015-09-02T09:35:11.130

Reputation: 67 575

1

Zsh, 15 bytes

<<<${#1//[!$2]}

Try it online!

Similar to the bash answer, but more compact thanks to Zsh allowing both ${ //} and ${# } in the same expansion.

GammaFunction

Posted 2015-09-02T09:35:11.130

Reputation: 2 838

1

Retina, 11 bytes

w`^(.)¶.*\1

Try it online!

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)

Sara J

Posted 2015-09-02T09:35:11.130

Reputation: 2 576

I'm pretty sure the ^ is unnecessary. If we can assume the string doesn't contain bad characters (seems like we can), ~\^[\n]K`` works (Try it online!). This might be possible to golf using something similar to that.

– my pronoun is monicareinstate – 2019-12-18T14:40:51.563

1

Burlesque, 4 bytes

peCN

Try it online!

Takes input as "string" 'i to search string for i.

If special inputs are not allowed:

Burlesque, 6 bytes

pe-]CN

Try it online!

Takes input as two quoted strings.

pe  # Parse and evaluate
CN  # Count

DeathIncarnate

Posted 2015-09-02T09:35:11.130

Reputation: 916

1

rs, 33 bytes

+(.)(.* (?!\1).)/\2
(.*)../(^^\1)

Live demo and test cases.

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

kirbyfan64sos

Posted 2015-09-02T09:35:11.130

Reputation: 8 730

1

C#, 36 51 48

Debug.Write(args[0].split(args[1][0]).Length-1);

Alex Carlsen

Posted 2015-09-02T09:35:11.130

Reputation: 387

Well now it will :) - Ofcourse I forgot the cw.. – Alex Carlsen – 2015-09-02T14:22:10.710

1You could also use Console.Write instead of Console.WriteLine to save another 4 bytes. – AdmBorkBork – 2015-09-02T14:23:29.950

I am such a fool -.- – Alex Carlsen – 2015-09-02T14:23:59.663

Doesn't Debug.Write go to STDERR rather than STDOUT? – Alex A. – 2015-09-03T01:51:47.040

1

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.

kirbyfan64sos

Posted 2015-09-02T09:35:11.130

Reputation: 8 730

The original style of invocation (+/=["hello";"l"]) worked fine in oK. The latter case (f:+/=;f["hello";"l"]) was behaving incorrectly and should be fixed now. – JohnE – 2015-09-02T21:42:43.640

@JohnE Uh, yeah. I was going to report that as a bug, but then I ended up entering another code golf challenge. :) – kirbyfan64sos – 2015-09-02T22:33:05.683

Nope, K doesn't beat APL this time. See my answer. You could call it a tie, but APL needs less additional chars during actual use. – Adám – 2015-09-03T04:11:53.537

1

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.

kirbyfan64sos

Posted 2015-09-02T09:35:11.130

Reputation: 8 730

1

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.

bmarks

Posted 2015-09-02T09:35:11.130

Reputation: 2 114

1

scala, 31 bytes

(x:String,y:Char)=>x.count(y==)

gilad hoch

Posted 2015-09-02T09:35:11.130

Reputation: 717

1

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.

DLosc

Posted 2015-09-02T09:35:11.130

Reputation: 21 213

1

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

David Arenburg

Posted 2015-09-02T09:35:11.130

Reputation: 531

1

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

Qwertiy

Posted 2015-09-02T09:35:11.130

Reputation: 2 697

1

Jelly, 1 byte (non-competing)

Non-competing since the question predates the language.

ċ

TryItOnline

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 ċ.

Jonathan Allan

Posted 2015-09-02T09:35:11.130

Reputation: 67 804

A string is an array of characters. The problem is that "o" is a string, not a character. As a function, plain ċ is enough. – Dennis – 2016-10-06T16:11:12.163

Wasn't sure of the rules on input, so made it a clause-1-byte-solution. Thanks! – Jonathan Allan – 2016-10-06T16:15:23.207

Do the command line arguments have to be entered as I have done in the TIO link? – Jonathan Allan – 2016-10-06T16:22:12.637

1There's no way of entering characters in the CLAs, since i put uses Python's syntax. You'd have to call the link with “onomatopoe”ç”o or similar. – Dennis – 2016-10-06T16:39:16.437

1

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:

Try it here.

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

Kevin Cruijssen

Posted 2015-09-02T09:35:11.130

Reputation: 67 575

1To get rid of the regex/replace, split on the character and count the resulting length a.split(b+"").length-1; -14 :D – Geobits – 2016-10-06T15:47:03.900

@Geobits Ah nice! Thanks. And here I thought I was smart by changing a.length-a.replace(b,"").length with a.replaceAll("[^"+b+"]","").length() to save a byte. xD – Kevin Cruijssen – 2016-10-06T17:19:07.343

1That was my original thought too (and I commented that first, but deleted), except I used the fixed 10 instead of a.length() since the length is fixed in the spec ;) – Geobits – 2016-10-06T17:20:37.417

1@Geobits Ah, good point. ;D But this is even better. ;) Also, managed to subtract an additional 2 bytes by changing the String+char parameters to String.... – Kevin Cruijssen – 2016-10-06T17:25:04.430

Good call. I always forget about the ... – Geobits – 2016-10-06T17:26:33.130

0

C, 55 bytes

t;c(char* i,char z){t=0;for(;*i;)t+=*i++==z;return t;}

Johan du Toit

Posted 2015-09-02T09:35:11.130

Reputation: 1 524

0

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

Try it online!

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.

steenbergh

Posted 2015-09-02T09:35:11.130

Reputation: 7 772

0

Wren, 29 bytes

Very hard to golf.

Fn.new{|a,b|a.count{|i|i==b}}

Try it online!

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}

Try it online!

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

user85052

Posted 2015-09-02T09:35:11.130

Reputation:

0

W, 4 bytes

Basically the same algorithm as my second Wren answer.

Sttk

user85052

Posted 2015-09-02T09:35:11.130

Reputation:

0

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

sporeball

Posted 2015-09-02T09:35:11.130

Reputation: 461

0

Ahead, 16 bytes

The first character on stdin is the counted character, and the remainder of stdin is the string.

i&>jlir
 @Or+=t<

Try it online!

snail_

Posted 2015-09-02T09:35:11.130

Reputation: 1 982

0

Fortran (GFortran), 60 bytes

character a(10),b
read('(10a,a)'),a,b
print*,count(a==b)
end

Try it online!

Takes input as an 11 length string, the last char being b.

DeathIncarnate

Posted 2015-09-02T09:35:11.130

Reputation: 916

0

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|oh

The 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|oh

The above can be used any number of times in the same environment.

Chad Baxter

Posted 2015-09-02T09:35:11.130

Reputation: 248