/**
* Return the number of occurances of the search character in the target string.
*
* @param target String to search.
* @param search Character to search string for.
*
* @throws {Error} If search params is not exactly one character.
*
* @example
* strCount('Hello', 'o') // => 1
* strCount('Hello', 'l') // => 2
* strCount('', 'z') // => 0
*/functionstrCount(target:string,search:string):number{if(!search||search.length!==1){thrownewError('Search character be exactly one character');}return(target.match(newRegExp(search,'g'))||[]).length;}
Java:
public static int strCount(String str, char letter) {
int count = 0;
for (char element : str.toCharArray()) {
if (element == letter) {
count++;
}
}
return count;
}
functionstrCount(text,letter){if(!letter.length){return'a letter is required.';}returntext.split('').filter(i=>i===letter).length;}console.log(strCount('Hello world',''))// a letter is required.console.log(strCount('Hello world','l'))// 3
funstrCount(str1:String,str2:String):Int{varcount=0varmatchIndex=0vari=0varindexOfFirstMatch=0while(i<str1.length){if(str1[i]==str2[matchIndex]){if(matchIndex==0){indexOfFirstMatch=i}if((++matchIndex)==str2.length){count++matchIndex=0i=indexOfFirstMatch+1}else{i++}}else{i++matchIndex=0}}returncount}funmain(){println(strCount("Hello","o"))println(strCount("Hello","l"))println(strCount("","z"))println(strCount("oh goodness gracious","o"))println(strCount("howdy, pardner","d"))println(strCount("Incumbent President","e"))// also it's fine tooprintln(strCount("Hello helllo","ll"))println(strCount("eeeeeee","ee"))}
I am an optimistic and hard worker Software engineer always looking forward to expand my knowledge and experience in the field, and go forward in my career.
TypeScript
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 returnundefinedso 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!
JavaScript
Swift solution :
Kotlin.
Python one liner,
Output,
C#
Python 3
JavaScript: