How do you count the occurrence of a given character in a string? code example
Example 1: c program to the count the number of times each character appears
#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a character to find its frequency: ");
scanf("%c", &ch);
for (int i = 0; str[i] != '\0'; ++i) {
if (ch == str[i])
++count;
}
printf("Frequency of %c = %d", ch, count);
return 0;
}
Example 2: count number of occurrences of character in string
public class CountStringOccurence {
public static void main(String[] args) {
int count= countOccurences("aaassssddadad",'s');
System.out.println(count);
}
private static int countOccurences(String word, char character){
int count = 0;
for(int i = 0; i < word.length(); i++){
if(word.chartAt(i) == character){
count++; }
}
return count;
}
}
Example 3: number of occurrences of character in string
public class CountStringOccurence {
public static void main(String[] args) {
int count= countOccurences("aaassssddadad",'s');
System.out.println(count);
}
private static int countOccurences(String word, char character){
int count = 0;
for(int i = 0; i < word.length(); i++){
if(word.chartAt(i) == character){
count++; }
}
return count;
}
}