Remove All Characters in a String Except Alphabets in C

Exercise:

Write a C Program to remove all characters in a string except alphabets.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    char line[150];
    printf("Enter the string: ");
    fgets(line, sizeof(line), stdin);
    for (int i = 0, j; line[i] != '\0'; ++i) {
        while (!(line[i] >= 'a' && line[i] <= 'z') && !(line[i] >= 'A' && line[i] <= 'Z') && !(line[i] == '\0')) {
            for (j = i; line[j] != '\0'; ++j) {
                line[j] = line[j + 1];
            }
            line[j] = '\0';
        }
    }
   printf("Output String: ");
   puts(line);
   return 0;
}
Click Here to View the Output!
Enter the string: It's price is 50 dollars
Output String: Itspriceisdollars
Click Here to View the Explanation!
  • This program is used to remove all the non-alphabet characters from a string.
  • In main(), a string array line is declared of the size 150.
  • The program requests the user to enter a string and stores it in line.
  • An outer for loop is initialized which iterates over the characters of the string and uses a while loop which checks the condition that if the current accessed character in the string is not an alphabet and is not a null character then that character will be removed.
  • An inner for loop will consider the non-alphabet character as the jth element of the string and it will be replaced by the (jth + 1) element. Hence, after the character removal, all the elements will be shifted to the left by one position.
  • The new string stored in the array line is then printed.