C Program to Remove All Characters in a String Except Alphabets

In this tutorial, i am going to show you how to remove all characters in a string except alphabets with the help of for loop and while loop in c programs.

All C Programs and Algorithm to Remove All Characters in a String Except Alphabets

  • Algorithm to Remove All Characters in a String Except Alphabets
  • C Program to Remove All Characters in a String Except Alphabets using For Loop
  • C Program to Remove All Characters in a String Except Alphabets using For and While Loop

Algorithm to Remove All Characters in a String Except Alphabets

Follow the below given algorithm to write a program to remove all characters in a string except alphabets; as follows:

  • Initialize the variables.
  • Accept the input from user.
  • Initialize a for or while loop.
  • Iterate each character through the loop.
  • Remove non alphabetical characters
  • Terminate for or while loop.
  • Print result.

C Program to Remove All Characters in a String Except Alphabets using For Loop

#include <stdio.h>
#include <string.h>
int main()
{
  char strAlphas[100];
  printf("Enter A String to Remove Non-Alphabets = ");
  fgets(strAlphas, sizeof strAlphas, stdin);
  int len = strlen(strAlphas);
  for (int i = 0; i < len; i++)
  {
    if (!(strAlphas[i] >= 'a' && strAlphas[i] <= 'z') || (strAlphas[i] >= 'A' && strAlphas[i] <= 'Z'))
    {
      for (int j = i; j < len; j++)
      {
        strAlphas[j] = strAlphas[j + 1];
      }
      len--;
      i--;
    }
  }
  printf("The Final String after Sorting Alphabetically = %s\n", strAlphas);
}

The result of the above c program; as follows:

Enter A String to Remove Non-Alphabets = [email protected]
The Final String after Sorting Alphabetically = hello

C Program to Remove All Characters in a String Except Alphabets using For and While Loop

#include <stdio.h>
int main()
{
    //Initializing variable.
    char str[100];
    int i, j;
    
     //Accepting input.
    printf(" Enter a string : ");
    gets(str);
     //Iterating each character and removing non alphabetical characters.
    for(i = 0; str[i] != '\0'; ++i)
    {
        while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') )
        {
            for(j = i; str[j] != '\0'; ++j)
            {
                str[j] = str[j+1];
            }
            str[j] = '\0'; 
        }
    }
     //Printing output.
    printf(" After removing non alphabetical characters the string is :");
    puts(str);
    return 0;
}

The result of the above c program; as follows:

Enter a string : [email protected]
After removing non alphabetical characters the string is :hello

More C Programming Tutorials

Be First to Comment

Leave a Reply

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