Here, we will write a C program to find the occurrence of a character in a string. Before that, you may go through the following topic in C.
We will look at two examples to calculate the frequency of characters in a string.
- For a particular character.
- For all the character in a string
C Program to Find the Frequency of Characters in a String (for a particular character)
Both the string and the character whose frequency needed to be found are entered by the user.
The questions: write a program in C to find the frequency of any given character in a given string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> int main() { char str[100], ch; int count = 0, i; printf("Enter the string: "); fgets(str, sizeof(str), stdin); printf("Enter a character whose frequency is to be found: "); scanf("%c", &ch); for (i = 0; str[i] != '\0'; ++i) { if (ch == str[i]) ++count; } printf("\nFrequency of %c = %d", ch, count); return 0; } |
Output:
Enter the string: This is simple2code.com
Enter a character whose frequency is to be found: i
Frequency of i = 3
C Program to Find the Frequency of Characters in a String (for all the characters)
The user needs to enter the string and the number of occurrences for each character will be displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> #include <string.h> int main() { char str[100], ch; int i, j, k, len, count = 0; printf("Enter the string: "); scanf("%s", str); len = strlen(str); for (i = 0; i < len; i++) { ch = str[i]; for (j = 0; j < len; j++) { if (ch == str[j]) { count++; for (k = j; k < (len - 1); k++) str[k] = str[k + 1]; len--; str[len] = '\0'; j--; } } printf("Frequency of %c = %d\n", ch, count); count = 0; i--; } return 0; } |
Output:
Enter the string: simple2code.com
Frequency of s = 1
Frequency of i = 1
Frequency of m = 2
Frequency of p = 1
Frequency of l = 1
Frequency of e = 2
Frequency of 2 = 1
Frequency of c = 2
Frequency of o = 2
Frequency of d = 1
Frequency of . = 1