DEV Community

Cover image for Coding Problem Interview Series: How to Count Character Occurrences in a String?
Ben Halpern Subscriber for CodeNewbie

Posted on

Coding Problem Interview Series: How to Count Character Occurrences in a String?

📣 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)

Collapse
 
nlxdodge profile image
NLxDoDge • Edited

In java something like this would do

String test = "Hello, World!";
String chr = "l";
long count = Arrays.stream(test.split("")).filter(chr::equals).count();
System.out.println(count);
Enter fullscreen mode Exit fullscreen mode

And make it a bit more re-usable by putting it in a utility class as a function.

class StringUtils {
    public static long charCountInString(String input, String search) {
        if(input == null || search == null) {
            return 0L;
        }
        return Arrays.stream(input.split("")).filter(search::equals).count();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, if you're more of a char guy you can do something like this

String test = "Hello, World!";
char chr = 'l';
long count = test.chars().filter(x -> x == chr).count();
System.out.println(count);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
chantal profile image
Chantal

Alright, so l tried this question in JavaScript cos that's the langguage l understand better hahahahaha.

Ok, so here we go:

function countOccurrences(string, char) {
  let count = 0;
  for (let i = 0; i < string.length; i++) {
    if (string.charAt(i) === char) {
      count++;
    }
  }
  return count;
}

Enter fullscreen mode Exit fullscreen mode

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:

const myString = "Hello, World!";
const character = 'l';
const occurrenceCount = countOccurrences(myString, character);
console.log(`The character '${character}' occurs ${occurrenceCount} times in the string.`);

Enter fullscreen mode Exit fullscreen mode

The Output:

The character 'l' occurs 3 times in the string.

Enter fullscreen mode Exit fullscreen mode

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!

Collapse
 
parimaldesign profile image
Parimal • Edited

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
Image description

Collapse
 
greyhound29 profile image
nathaniel jenkeo

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());
}
}}}}}

Collapse
 
goldins profile image
Simon Goldin

quick JS implementation:

const countLetter = (searchStr, letter) => searchStr.split(letter).length - 1;

countLetter('hello and happy Monday!', 'a'); // 3
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nihmrnd profile image
Nicole

In python:

word = 'Test'
count = 0

for letter in word:
  if letter.lower() == 't':
    count += 1

print(count)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
soumyadeepdey profile image
Soumyadeep Dey ☑️

🤔