C Program to Remove all Characters in a String Except Alphabets
ADVERTISEMENTS
C program to remove all characters in a string except alphabets.
In this article, you will learn how to remove all characters from a given string like special characters, numeric digits, etc except only alphabets (small + capital letters).
To solve this problem, we'll use the for loop
and while loop
.
Example
Enter a Sentence: #$comp%!2ute)(r
Filtered Sentence: computer
Filtered Sentence: computer
You should know about the following topics in C programming to understand this program:
- C For loop
- C While loop
- C Arrays
Source
// C program to Remove all Characters in a String Except Alphabets
#include <stdio.h>
// It's the main function of the program
int main() {
char sentence[1000];
// Step-1 Take input sentence from User
printf("Enter a Sentence: ");
fgets(sentence, sizeof(sentence), stdin);
// Step-2 Loop over the `sentence` variable to iterate each character of the sentence
for (int i = 0, j; sentence[i] != '\0'; i++) {
// Remove all the characters except alphabets
while (!(sentence[i] >= 'a' && sentence[i] <= 'z') && !(sentence[i] >= 'A' && sentence[i] <= 'Z') && !(sentence[i] == '\0')) {
// Accept only alphabet characters in the `sentence` variable
for (j = i; sentence[j] != '\0'; j++) {
sentence[j] = sentence[j + 1];
}
sentence[j] = '\0';
}
}
// Step-3 Final output of the program
printf("Filtered Sentence: ");
puts(sentence);
return 0;
}
Output
Enter a Sentence: w3c@#%ode&^wo)(1rld
Filtered Sentence: wcodeworld