C++ Programming

Write a C++ program to remove all special characters from a given string.

Method 1

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

string removeAllSpecialCharacters(const string& str)
{
string output;
for (char ch : str) {
// Check if character is alphanumeric or whitespace
if (isalnum(ch) || isspace(ch)) 
{ 
// Keep alphanumeric characters and spaces
output += ch;
}
}
return output;
}

int main() {
string input;
cout << "Enter any sentence: ";
getline(cin, input);

string newString = removeAllSpecialCharacters(input);
cout << "New sentence after removing of special characters: "<< newString <<endl;

return 0;
}

Output

Enter any sentence: This is a sentence with @special character #$
New sentence after removing of special characters: This is a sentence with special character
  • The  function [isalnum] checks if a character is alphanumeric. 
  • The  function [isspace] checks if a character is a whitespace character.
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments