 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Remove all Characters in a String Except Alphabets
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;
Advertisements
                    