Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently remove double quotes from std::string if they exist

Tags:

c++

stdstring

This question risks being a duplicate e.g. remove double quotes from a string in c++ but none of the asnwers that I saw addresses my question
I have a list of strings, some of which are double quoted and some aren't, Quotes are always at beginning and end

std::vector<std::string> words = boost::assign::list_of("words")( "\"some\"")( "of which")( "\"might\"")("be quoted");

I am looking for the most efficient way to remove the quotes. Here is my attempt

for(std::vector<std::string>::iterator pos = words.begin(); pos != words.end(); ++pos)
{
  boost::algorithm::replace_first(*pos, "\"", "");
  boost::algorithm::replace_last(*pos, "\"", "");
  cout << *pos << endl;
}

Can I do better than this? I have potentially hundreds of thousands of string to process.They may come from a file or from a database. The std::vector in the example is just for illustration purposes.

like image 800
molita Avatar asked Sep 11 '11 14:09

molita


2 Answers

If you know the quotes will always appear in the first and last positions, you can do simply

if ( s.front() == '"' ) {
    s.erase( 0, 1 ); // erase the first character
    s.erase( s.size() - 1 ); // erase the last character
}

The complexity is still linear in the size of the string. You cannot insert or remove from the beginning of a std::string in O(1) time. If it is acceptable to replace the character with a space, then do that.

like image 173
Potatoswatter Avatar answered Oct 19 '22 21:10

Potatoswatter


It would probably be fast to do a check:

for (auto i = words.begin(); i != words.end(); ++i)
    if (*(i->begin()) == '"')
        if (*(i->rbegin()) == '"')
            *i = i->substr(1, i->length() - 2);
        else
            *i = i->substr(1, i->length() - 1);
    else if (*(i->rbegin()) == '"')
        *i = i->substr(0, i->length() - 1);

It might not be the prettiest thing ever, but it's O(n) with a small constant.

like image 20
Seth Carnegie Avatar answered Oct 19 '22 19:10

Seth Carnegie