Removing double quotes from string in C++

In this tutorial, we are going to learn how to remove double quotes from a string in C++.
We can do this by using erase() function.
Basically, what is the work of erase() function? It removes the elements from a vector or a string in some range. We are going to use this function to remove the double quotes in a string.

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    string str;
    cout<<"Enter the string"<<endl;
    getline(cin,str);
    str.erase(std::remove(str.begin(),str.end(),'\"'),str.end());
    cout<<str;
    return 0;
}


Output:

  Enter the string
  "She is good looking"
  She is good looking

Explanation: Remove double quotes from a string in C++

  1. First of all, include all the required libraries. Like for my code , <algorithm> was a must library . This is because remove() and erase() functions used are basically algorithms.They are present in <algorithm> header file.
  2. Take a string containing double quotes as an input.
  3. Now apply the erase function.Now if you see, I have used remove() function inside erase() function. This function also removes an element from the vector or a specified range.
  4. Now simply print the string to see the output.

Erase() function requires 3 parameters as per its syntax. Basic syntax is:

erase(start,end,char)

start: This is the position from where start processing our string. With reference to my code, starting index is obtained by calling begin() function.

end: This is the position till where we have to process our string. Here in my code, I have used end() function to obtain the last index.

char: This is what we have to remove from our string. I have to remove double quotes(“”), so I have mentioned it in the third parameter.




You may also read,


Leave a Reply

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