C++ Program to Remove all Characters in a String Except Alphabets

C++ProgrammingServer Side Programming

A string is a one-dimensional character array that is terminated by a null character. It may contain characters, digits, special symbols etc.

A program to remove all characters in a string except alphabets is given as follows.

Example

#include <iostream>
using namespace std;
int main() {
   char str[100] = "String@123!!";
   int i, j;
   cout<<"String before modification: "<<str<<endl;
   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];
         }
      }
   }
   cout<<"String after modification: "<<str;
   return 0;
}

Output

String before modification: String@123!!
String after modification: String

In the above program, the string modification is done in a for loop. If the character in the string is not an alphabet or null, then all the characters to the right of that character are shifted towards the left by 1. This is done using j in the inner for loop. This leads to the removal of the non alphabetic character. A code snippet that demonstrates this is as follows −

Example

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];
      }
   }
}

After modification, the string is displayed. This is shown below −

cout<<"String after modification: "<<str;
raja
Published on 05-Oct-2018 11:04:47
Advertisements