Removing quotes from a string

Sep 15, 2009 at 11:33am
Hi,

I'm new at C++ and I with some source I've found online I was able to copy a textfile to a string. But the textfile consists out of words with (double) quotes. And I want to remove all the (double) quotes in text. But I have no idea how to. Tried some stuff with replace etc. but nothing worked.. can anybody help me out?

Greetings, LuQ

In the string they are put in all quotes are probably escaped, (since it doesnt gives any error), but the textfile looked like this:

 
Some text with "random" quotes " in it. I want to " remov"e them.  


Last edited on Sep 15, 2009 at 11:36am
Sep 15, 2009 at 1:06pm
 
std::string::find( '"' );


will return std::string::npos if there are no double quotes in the string or the index of the first one.

 
std::string::erase( pos, count );


will remove "count" characters from the string beginning at position pos.

Write the following loop (pseudo-code):

1
2
3
4
5
first_quote = find_first_quote( str );
while ( there is a first_quote ) {
    erase_first_quote( str, first_quote );
    first_quote = find_first_quote( str );
}

Sep 15, 2009 at 7:37pm
There's a standard algorithm to do that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int main()
  {
  string s;
  cout << "Please enter a string containing \"double-quotes\"\n> " << flush;
  getline( cin, s );

  // Remove all double-quote characters
  s.erase(
    remove( s.begin(), s.end(), '\"' ),
    s.end()
    );

  cout << s << endl;
  return 0;
  }

Hope this helps.
Sep 16, 2009 at 9:25am
Ok thank you very much! I will test it this afternoon, I think (and hope) both solutions will fit. Thanks again for the quick response.

Edit:

It works, I've managed to store it in a class (my first one ever hehe). Both solutions work by the way!
Last edited on Sep 17, 2009 at 7:10am
Topic archived. No new replies allowed.