(C programming Example for Beginners)
C Program to Remove all Characters in a String Except Alphabets
In this example, you will learn to remove all the characters from a string entered by the user except the alphabets.
Remove Characters in String Except Alphabets
#include <stdio.h>
int main(){
char line[150];
printf("Enter a string: ");
fgets(line, sizeof(line), stdin); // take input
for (int i = 0, j; line[i] != ''; ++i) {
// enter the loop if the character is not an alphabet
// and not the null character
while (!(line[i] >= 'a' && line[i] <= 'z') && !(line[i] >= 'A' && line[i] <= 'Z') && !(line[i] == '')) {
for (j = i; line[j] != ''; ++j) {
// if jth element of line is not an alphabet,
// assign the value of (j+1)th element to the jth element
line[j] = line[j + 1];
}
line[j] = '';
}
}
printf("Output String: ");
puts(line);
return 0;
}
Output
Enter a string: p2'r-o@gram84iz./ Output String: programiz
This program takes a string input from the user and stores in the line variable. Then, a for
loop is used to iterate over characters of the string.
If the character in a string is not an alphabet, it is removed from the string and the position of the remaining characters are shifted to the left by 1 position.
C Example for Beginners: C Program to Remove all Characters in a String Except Alphabets
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.