C++ Program to remove all characters from a string object except alphabets


January 21, 2023, Learn eTutorial
1091

In this C++ program, you will learn to remove all characters from a string except alphabets.

Define string in C++.

A string can be defined as a sequence of characters. In C++ there are two types of strings which are,

  • Strings that are objects of the string class 
  • C-strings (C-style Strings)

  In C++, you can create a string object for holding strings. Unlike using arrays, string have no fixed length.

How to remove all characters except alphabets in a string using C++ program?

Here our program takes a string object input from the user. Then declare two string objects; string line and string temp. Ask the user to enter a string. Read the string entered by the user to the string object line. Here, we are using the function getline() to get the entered line of text by the user. 

The string entered by the user is stored in the string object line. Now, we have to extract all the characters that are not alphabets from the string. For this, we have to compare each character of the string with the alphabets from 'a to z' and 'A to Z'. For accessing each of the elements in the string we can use a for loop.

Get each character and perform the comparison with the alphabet using the if condition. if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) and add the element to the object temp if it is an alphabet. Temp= temp + line[i]. Finally, we get the string with only alphabets and display the output.

ALGORITHM

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare two string type objects; string line; string temp;

Step 5: Ask the user to enter the string.

Step 6: get the string into the object line using the function getline().

Step 7: Access the characters of the string from the beginning and compare each of the characters with alphabets a to z and A to Z. 

Step8:If it matches then store the character to the object temp.

Step 9: Get the string free from characters that are non-alphabets from the object temp.

Step 10: Display the string;

Step 11: Exit.

C++ Source Code

                                          #include <iostream>
using namespace std;

int main() {
    string line;
    string temp = "";

    cout << "Enter a string: ";
    getline(cin, line);

    for (int i = 0; i < line.size(); ++i) {
        if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
            temp = temp + line[i];
        }
    }
    line = temp;
    cout << "Output String: " << line;
    return 0;
}
                                      

OUTPUT

Enter a string: l4ea@rne$$45tuto87ria**ls
Output String: learnetutorials