Removing Characters Except Alphabets From a String in C++

Exercise:

Write a C++ program that can be used to remove all characters from a string except alphabet characters.

Program 1: String Object

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main() 
{
    string words , temp = "";
    cout << "Insert a sentence with special characters: ";
    getline(cin, words);
    for (int i = 0; i < words.size(); ++i)
    {
        if ((words[i] >= 'a' && words[i] <= 'z') || (words[i] >= 'A' && words[i] <= 'Z'))
        {
            temp = temp + words[i];
        }
    }
    words = temp;
    cout << "\nSentence without characters: " << words;
    return 0;
}
Click Here to View the Output:
Insert a sentence with special characters: #co74*d!e o8-f +co"d>e
Sentence without characters: codeofcode
Click Here to View the Explanation:
  • Two variables are initialized temp, and words. for loop is used to remove all characters except alphabets.
  • The rest of the line is saved in a variable and then printed onto the screen.

Program 2: C Style String

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main() 
{
    char words[100] , str[100];
    int x =0;
    cout << "Insert a sentence with special characters: ";
    cin.getline(words, 100);
    for (int i = 0; words[i] != '\0' ; ++i)
    {
        if ((words[i] >= 'a' && words[i] <= 'z') || (words[i] >= 'A' && words[i] <= 'Z'))
        {
            str[x++] = words[i];
        }
    }
    str[x] = '\0';
    cout << "\nSentence without characters: " << str;
    return 0;
}
Click Here to View the Output:
Insert a sentence with special characters: #co74*d!e o8-f +co"d>e
Sentence without characters: codeofcode
Click Here to View the Explanation:
  • This code is similar to the code above. The only difference is that this code took C Style string from the user and the previous took string object.