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

Updated on December 11, 2024
Remove all characters in a string except alphabets. header image

Introduction

In programming, particularly in C++, string manipulation is a frequent and important task. One such task involves filtering out non-alphabetic characters from a string, simplifying it to contain only letters. This operation is critical in applications such as data validation, parsing, and preprocessing before database insertion or computational analysis.

In this article, you will learn how to remove all characters from a string in C++ that are not alphabets. Through detailed examples, you'll see various methods such as using standard library functions and loops, allowing you to choose the right approach depending on your specific project requirements.

Method 1: Using C++ Standard Library Functions

When dealing with strings in C++, the Standard Template Library (STL) offers powerful tools that can simplify operations like character removal.

Using remove_if and erase

  1. Include the headers <iostream> for standard I/O operations and <algorithm> for the remove_if algorithm.

  2. Create a string filled with mixed characters.

  3. Apply the remove_if function with a lambda expression to identify and rej1ect non-alphabetic characters, followed by erase to remove them.

    cpp
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main() {
        string str = "Hello! World, 2023.";
        str.erase(remove_if(str.begin(), str.end(), [](char c) {
            return !isalpha(c);
        }), str.end());
        cout << str << endl;
        return 0;
    }
    

    The lambda function [](char c) { return !isalpha(c); } checks if a character is not an alphabet. If it's true, remove_if moves it to the end of the string. The erase function then removes these characters from the string. After execution, it prints HelloWorld.

Using copy_if with Back Insertion

  1. Employ a new string to hold the filtered result.

  2. Use copy_if with similar criteria for alphabetic characters.

  3. Print the readable result.

    cpp
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    using namespace std;
    
    int main() {
        string inputString = "C++ 2023! @ Programming";
        string outputString;
        copy_if(inputString.begin(), inputString.end(), back_inserter(outputString), [](char c) {
            return isalpha(c);
        });
    
        cout << outputString << endl;
        return 0;
    }
    

    This snippet uses copy_if to replicate only the alphabetic characters into a new string. The back_inserter constructs the new string by appending at the end. This results in printing CPPProgramming.

Method 2: Using Traditional Loops

Sometimes, STL methods may seem complex or may not fit the context, especially when specific conditions beyond simple checks are needed. A traditional loop can provide more explicit control over each character.

Using a For Loop

  1. Iterate through each character of the string.

  2. Check if the character is an alphabetic character using isalpha function.

  3. Append alphabetic characters to a new string if they pass the check.

  4. Display the cleaned string.

    cpp
    #include <iostream>
    #include <cctype>  // For isalpha function
    
    using namespace std;
    
    int main() {
        string srcStr = "Hello 432, World!";
        string destStr;
    
        for (char c : srcStr) {
            if (isalpha(c)) {
                destStr += c;
            }
        }
    
        cout << destStr << endl; // Outputs: HelloWorld
        return 0;
    }
    

    This example leverages basic loop iteration, checking each character and assembling a new string exclusively with alphabetic characters.

Conclusion

Removing all characters from a string except alphabets in C++ can be achieved utilizing various techniques. Whether using the potent STL functions like remove_if with erase, copy_if with back insertion, or a straightforward for-loop, you can maintain flexibility in your approach based on your project's needs. These methods not only provide clean and efficient solutions but also enhance the modularity and readability of your code. Employ these strategies in future C++ projects to handle textual data efficiently and effectively.