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

When working with strings in C++, it may be necessary to remove certain characters from the string while keeping only the alphabets.

This can be achieved by writing a simple program that loops through each character in the string and removes any non-alphabetic characters.

To start, we will define a function called “removeNonAlphabets” that takes a string as input and returns the modified string.

The function will use a for loop to iterate through each character in the string and check if it is an alphabet. If it is not, the character will be removed from the string.

Here is the implementation of the function:

#include <iostream>
#include <string>

using namespace std;

string removeNonAlphabets(string input) {
    string output = "";
    for (int i = 0; i < input.length(); i++) {
        if (isalpha(input[i])) {
            output += input[i];
        }
    }
    return output;
}

int main() {
    string input = "Hello123World";
    string output = removeNonAlphabets(input);
    cout << "Input: " << input << endl;
    cout << "Output: " << output << endl;
    return 0;
}

In this program, the “isalpha” function is used to check if the current character is an alphabet. If it is, the character is added to the output string. If not, it is skipped.

Let’s walk through the code step by step. First, we include the necessary libraries for the program.

Then, we define the “removeNonAlphabets” function that takes a string as input and returns the modified string.

Inside the function, we declare an empty string called “output” that will store the modified string.

We then loop through each character in the input string using a for loop. For each character, we check if it is an alphabet using the “isalpha” function.

If it is, we append it to the “output” string using the “+=” operator. If it is not, we skip it. Finally, we return the modified string.

In the main function, we declare an input string and call the “removeNonAlphabets” function to get the modified string. We then print both the input and output strings to the console.

This program is a simple and efficient way to remove all non-alphabetic characters from a string in C++.

It can be used in a wide range of applications where data cleansing is necessary.