How to remove special characters from a string in C++

In this tutorial, we will learn how to remove special characters from a given string in C++.


#include <iostream>
using namespace std;

int main() {
    string str="co//de??spe;,edy";  //initializing a string
    string temp = ""; //initializing a temporary string
    cout<<"initial string is: "<<str<<endl;

    for (int i = 0; i < str.size(); ++i) 
        if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) //initializing condition  
            temp = temp + str[i];//passing characters that match condition to temp string from initialized string
    str = temp;//initializing temp as new string 
    cout << "modified String is: " << str;//getting output
    return 0;

Code Explanation

  1. In this code first, we have initialized two string variables “str” and “temp”.
  2. In “str” we have taken our string which has special characters aside from the alphabets.
  3. After that, we initialized a for loop inside which we used an “If” statement to check every character present in the string.
  4. Condition is that every character present in the string that lies in between “a” and “z” or “A” and “Z” will get a pass to “temp”.
  5. On every iteration of for loop, each character of the given string will be checked one by one.
  6. If the condition is matched then that character will be passed to “temp” from “str”.
  7. Finally, we are initializing “temp” as our new “str” and getting output.


initial string is: co//de??spe;,edy
modified String is: codespeedy

Initially, we took a string “co//de??spe;,edy” which has special characters and we got “codespeedy” as our output string.

Leave a Reply

Your email address will not be published. Required fields are marked *