In this tutorial you will learn about the C Program to find All Occurrence of a Character in a String and its application with practical example.
C Program to find All Occurrence of a Character in a String.
In this tutorial, we will learn to create a C program that will Find All the Occurrence of a Character in a String in C programming
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C programming.
- Conditional Statements in C programming.
What is the Occurrence of a string?
The frequency of a string means the number of occurrences of alphabets in the string. As we know the String is a collection of characters and words. The word is a collection of alphabets. For frequency, the letters are counted in the string individually and the result will show the statistics for the frequency.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
1. Declaring the variables for the program. 2. Taking the input string from the user. 3. Finding the size of string 4. Passing those variables to for loop. 5. Using conditional statements for the program to find the first occerence of word. 6. Printing the result position. 7. End the program. |
Find All the Occurrence of a Character in a String
In this program first, we will take input string from the user. Then will find the Occurrence of each Character in a String in that string by counting the occurrence of each character. Printing the Occurrence of that character.
Let us take the example program from the below code to find the Occurrence of each Character in a String.
Program:-
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 38 |
/* C Program to Find <strong>Occurrence </strong>of each Character in a String */ #include <string.h> int main() { //declaring the required variables for the program char s[1000]; int i,j,k,flag=0,n; //Taking the input string from the user. printf("Enter the string : "); gets(s); //finding the length of string for(j=0;s[j];j++); n=j; printf(" <strong>Occurrence </strong>count character in string:\n"); //Finding the <strong>Occurrence </strong> of the characters for(i=0;i<n;i++) { flag=1; if(s[i]) { for(j=i+1;j<n;j++) { if(s[i]==s[j]) { flag++; s[j]='\0'; } } //Printing the <strong>Occurrence </strong>of the characters printf(" '%c' = %d \n",s[i],flag); } } return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- s[1000] = it will hold the string value.
- j = it will hold the integer value.
- i = it will hold the integer value.
- k = it will hold the integer value.
- flag = it will hold the integer value
Input string from the user for the program.
Finding the length of the string.
Finding the Occurrence of the characters in the string.
Printing output Occurrence of the characters.