C++ Program to Remove all Non Alphabet Characters from a String

Here is a C++ program to remove all non alphabet characters from string. To delete all non alphabet characters from a string, first of all we will ask user to enter a string and store it in a character array. Then using a for loop, we will traverse input string from first character till last character and check for any non alphabet character. If we found a non alphabet character then we will delete it from input string.

Finally, we will print modified output string on screen using cout.

For Example :
Input : 53^appl*e
Output : apple

Input :  123abcd_45
Output : abcd

Algorithm to Delete non Alphabet characters from String
Let "inputString" be the string entered by user of length N.
  • Initialize two variables i and j to 0 and -1 respectively.
  • Using a loop, traverse the inputString from index i=0 to i=N-1.
  • For every character inputString[i],check if it is an alphabet character. If true then copy it at inputString[j] and increment j otherwise continue.
  • After the end of for loop, set inputString[j] = '\0'. Now output string is from index 0 to j.

C++ Program to Remove all characters from a string except Alphabet

#include <iostream>
using namespace std;

int main() {
    char inputString[200];
    int i, j;
    cout << "Enter a string\n";
    cin.getline(inputString, 200);
 
    for(j = -1, i = 0; inputString[i] != '\0'; i++) {
        if((inputString[i]>='a' && inputString[i]<='z') || 
      (inputString[i]>='A' && inputString[i]<='Z')) {
            inputString[++j] = inputString[i];
        }
    }
    inputString[j] = '\0';

    cout << "Output : " << inputString;

    return 0;
}
Output
Enter a string
age#76jhg!&
Output : agejhg

Recommended Posts
C++ Program to Check Whether a Character is Alphabet or Not
C++ Program to Check Whether a Character is Vowel or Consonant
C++ Program to Print Multiplication Table of a Number
C++ Program to Display Fibonacci Series using Loop and Recursion
C++ Program Linear Search in Array
C++ Program to Find Factorial of a Number
C++ Program to Find Largest of Three Numbers
C++ Program to Find LCM and GCD of Two Numbers
C++ Program to Swap Two Numbers
C++ Program to check Whether a Number is Palindrome or Not
C++ Program to Check Prime Number Using Function
All C++ Programs