C Program to Remove Characters in String Except Alphabet

Here we will write a C program to remove all characters in a string except the alphabet. If the string was “[email protected]” then the result in the string will be “KnowProgram”.

C Program to Remove all Characters in a String except Alphabet using another String

#include<stdio.h>
int main()
{
   char s1[100],s2[100];
   int i, j;

   printf("Enter string: ");
   fgets(s1, sizeof(s1), stdin);

   for(i=0,j=0;s1[i]!='\0';i++)
   {
     if((s1[i]>='A' && s1[i]<='Z')||(s1[i]>='a' && s1[i]<='z'))
     {
        s2[j]=s1[i];
        j++;
     }
   }
   s2[j]='\0';

   printf("Displaying string: %s",s2);
   return 0;
}

Output for the different test-cases:-

Enter string: #[email protected]
Displaying string: KnowProgram

Enter string: [email protected] Welcome, To The Programming World!
Displaying string: HelloWelcomeToTheProgrammingWorld

This is the easiest way. In this program, we checked every character of the string. Only the character whose ASCII value is in between (including) ‘a’ to ‘z’ or ‘A’ to ‘Z’ those characters are an alphabet. Our problem was to remove all the characters except alphabet from the string. So, we checked every character of the string, if the character is an alphabet then copy it to second string. By this way finally, we get a string which has the only alphabet.


Without using Another String

#include<stdio.h>
int main()
{
   char s[150];
   int i, j;

   printf("Enter a string: ");
   fgets(s, sizeof(s), stdin);

   for(i = 0; s[i] != '\0'; ++i)
   {
     while (!( (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <='Z') || s[i] == '\0') )
     {
       for(j = i; s[j] != '\0'; ++j)
       {
         s[j] = s[j+1];
       }
       s[j] = '\0';
     }
   }

   printf("Output String: %s",s);
   return 0;
}

Output:-

Enter a string: ComputerA4002020Corner
Output String: ComputerACorner

In this program, we will do the same thing without using another string. If any character in the string is not an alphabet then the next character is replaced.

PrepBytes
Use Code KNOWPROGRAM10 to get FLAT 10% OFF on all Courses

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

More C programming Examples on String

Leave a Comment

Your email address will not be published. Required fields are marked *