In this tutorial you will learn about the C Program to find Characters in a String and its application with practical example.
C Program to find Characters in a String
In this tutorial, we will learn to create a C program that will Find the Characters 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.
Character in a string:-
The finding of a character in 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 finding the characters, the letters are counted in the string individually and the result will show the statistics for the character.
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 character in the string. 6. Printing the result position. 7. End the program. |
Find the Character in a String:-
In this program first, we will take input string from the user. Then we will take the character to be searched from the user. Then will find the number of Characters in a String by counting the occurrence of that character. Printing the number of characters in that string.
Let us take the example program from the below code to find the 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 |
/* C Program to Find Character in a String */ #include <stdio.h> int main() { //Declaring the variable for the program char str[1000], chr; int flag = 0; //Taking input sting from the user. printf("Enter a string: "); fgets(str, sizeof(str), stdin); //Taking the character in the input to find in the string. printf("Enter a character to find it in string: "); scanf("%c", &chr); //Finding the character in the string. for (int i = 0; str[i] != '\0'; ++i) { if (chr == str[i]) ++flag; } //Printing the output for the program. printf("Charaters in the word %c = %d", chr, flag); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- str[1000] = it will hold the string value.
- chr = it will hold the string value.
- flag = it will hold the integer value.
Input string from the user for the program.
Taking the input character from the user.
Finding the characters in the string.
Printing output number of the characters in the string.