Create a function called that accepts 2 string arguments and returns an integer of the count of occurrences the 2nd argument is found in the first one.
If no occurrences can be found, a count of 0 should be returned. The first argument can be an empty string. The second string argument must be of at least length 1.
Examples
strCount('Hello', 'o') // => 1
strCount('Hello', 'l') // => 2
strCount('', 'z') // => 0
Tests
strCount('oh goodness gracious', 'o')
strCount('howdy, pardner', 'd')
strCount('Incumbent President', 'e')
Good luck!
This challenge comes from shaddyjr on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (14)
TypeScript
JavaScript
Java:
public static int strCount(String str, char letter) {
int count = 0;
for (char element : str.toCharArray()) {
if (element == letter) {
count++;
}
}
return count;
}
Love it!
JS using a different approach, recursive function
The readable version
One line version
Actually,
string[index out of bound]
will returnundefined
so you don't need to check that your index is lower than the length of the string.Also, you don't need to keep track of the characters' count if you just return it right in your recursive call.
And you can increment your index right when you access your character for comparison.
If you are about the bytes, this makes it for a shorter version of your solution.
You are right, thanks!
Python one liner,
Output,
Kotlin.
Swift solution :
C#
Python 3
JavaScript: