Frontend Tech Lead, 15+ years. I structure large React/TypeScript monorepos so many teams can ship fast. Building IsoLoop, an open-source event-loop isolation runtime for web apps.
/**
* 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.
Frontend Tech Lead, 15+ years. I structure large React/TypeScript monorepos so many teams can ship fast. Building IsoLoop, an open-source event-loop isolation runtime for web apps.
JS using a different approach, recursive function
The readable version
One line version
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!
JavaScript
Swift solution :
Kotlin.
Python one liner,
Output,
C#
Python 3
You are right, thanks!
JavaScript: