C Program to Remove all Characters in a String Except Alphabets

C Topics Find the Frequency of Characters in a String Check Whether a Character is an Alphabet or not Display Characters from A to Z Using Loop Count

 To understand this example, you should have the knowledge of the following C programming topics:

 

·       C Arrays

·       C Multidimensional Arrays

·       Pass arrays to a function in C

·       C for Loop

·       C Arrays

·       C Pointers

·       Relationship Between Arrays and Pointers

·       C Pointers

·       C Pass Addresses and Pointers

·       C Dynamic Memory Allocation

·       C Programming Strings

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] != '\0'; ++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] == '\0')) {
         for (j = i; line[j] != '\0'; ++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] = '\0';
      }
   }
   printf("Output String: ");
   puts(line);
   return 0;
}

Output

Enter a string: soft2'w-a@ret84echit./
Output String: softwaretechit

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.

 

Labels : #c ,#code ,#examples ,

Post a Comment