📣 Calling experienced devs and recent interviewees! Join the "Coding Problem Interview Series" to help code newbies tackle interview questions assessing problem-solving skills, algorithmic knowledge, and implementation of sorting, string manipulation, and data structure algorithms.
Share your expertise and insights! Pleas share multiple perspectives and tips for standout answers!
Today's question is:
How would you write a function to count the occurrence of a specific character in a given string?
Follow the CodeNewbie Org and #codenewbie for more discussions and online camaraderie!
Top comments (7)
In java something like this would do
And make it a bit more re-usable by putting it in a utility class as a function.
Now, if you're more of a char guy you can do something like this
Alright, so l tried this question in JavaScript cos that's the langguage l understand better hahahahaha.
Ok, so here we go:
So in this JavaScript function, string is the input string, and char is the character you want to count.
Let's try to put it into something real:
The Output:
The function uses a for loop to iterate over each character of the input string. It checks if the character at the current index is equal to the specified character. If there is a match, it increments the count variable. Finally, it returns the count of occurrences.
Ok, guys so that's it. I'm a junior too and l would love to learn from your corrections. Feel free to correct me!
ChatGPT gave same answer and example you even as a junior you're coding on par with GPT, so you have got no reason to worry
public class sort{
public static void main(String [] args){
try{
String [] match ;
String s = "winter soldier ";
String v = " summer ";
boolean found = false ;
for ( i=0 ; i<s.length();i++){
if(s.charAt(i) == v.charAt[i]){
found = true ;
count=+1;
System.out.print(count + "are matched indexes ");
}catch(Exception e){
System.out.println(e.getMessage());
}
}}}}}
quick JS implementation:
In python:
🤔