Remove Punctuations From A String In C++

What we are going to see through this article is we will see in detail Remove Punctuations From A String In C++. We are required to write a C++ function that takes in a string and removes all special characters from the string leaving behind just alphabets and numerals in the resultant string.

Following is the list of Punctuations used in sentences. If the sentence has any of the following punctuations we want to remove it.

                                 !"#$%&'()*+,-./:;?@[\]^_`{|}~ 

Example:

Input 1 : &Visit our Website "CodingDiksha.com"!
Output 1 : Visit our Website CodingDikshacom

Input 2 : $$$$DivyaKrishnaKumar$$$$
Output 2 : DivyaKrishnaKumar
Remove Punctuations From A String In C++

Remove Punctuations From a String in C++

// CPP program to remove punctuation from a given string
 
#include <iostream>
using namespace std;
 
int main()
{
    // input string
    std::string str = "Welcome???@@##$ to#$% Coding%$^$%^&Diksha";
 
    for (int i = 0, len = str.size(); i < len; i++)
    {
        // check whether parsing character is punctuation or not
        if (ispunct(str[i]))
        {
            str.erase(i--, 1);
            len = str.size();
        }
    }
     
    // print string without punctuation
    std::cout << str;
    return 0;
}

Read Also: C++ Program To Sort Words In Alphabetic Order

Output

Welcome to CodingDiksha

Final Words

What we learned through this article is to Remove Punctuations From A String In C++. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment