Solved

STL string function to strip quotes

Posted on 2004-04-01
11
1,311 Views
Last Modified: 2007-12-19

I need a function using strings that will:
    check the string for beginning and ending quotes
    if quotes are present, strip them and return the string
    if the quotes are not there just return the string

This seems like it should be easy but I am new to using strings and can't get it to work.
I finally gave up and used character arrays.

Here is what I had with the strings:

string StripQuotes(string in)
{
    string out = in;
    if(out.at(0), '\"')
    {
        out.erase(0);
        int end = out.find('\"', 1);
        if(end != out.npos)
        {
            out.erase(end-2);
        }
    }

    return out;
}

What is wrong with the above function or
is there a better way to do this?

Thanks,
-jimp
0
Comment
Question by:jpattee
11 Comments
 
LVL 30

Assisted Solution

by:Axter
Axter earned 150 total points
ID: 10736789
Here's a set of trim functions for string.

      void Trim(std::string& str, const std::string & ChrsToTrim = " \t\n\r", int TrimDir = 0)
      {
            size_t startIndex = str.find_first_not_of(ChrsToTrim);
            if (startIndex == std::string::npos){str.erase(); return;}
            if (TrimDir < 2) str = str.substr(startIndex, str.size()-startIndex);
            if (TrimDir!=1) str = str.substr(0, str.find_last_not_of(ChrsToTrim) + 1);
      }

      inline void TrimRight(std::string& str, const std::string & ChrsToTrim = " \t\n\r")
      {
            Trim(str, ChrsToTrim, 2);
      }
      
      inline void TrimLeft(std::string& str, const std::string & ChrsToTrim = " \t\n\r")
      {
            Trim(str, ChrsToTrim, 1);
      }
0
 
LVL 30

Expert Comment

by:Axter
ID: 10736798
Example usuage:

std::string Data = "\"Hello World\"";

TrimRight(Data, "\"");
TrimLeft(Data, "\"");
0
 
LVL 30

Expert Comment

by:Axter
ID: 10736809
Oops! Correction:

Example usuage:

std::string Data = "\"Hello World\"";

Trim(Data, "\"");

If you just call Trim, it will trim both right and left.
0
 
LVL 30

Expert Comment

by:Axter
ID: 10736832
Here's a modified version for your function.

string StripQuotes(string in)
{
      string str = in;
      string ChrsToTrim = "\"";
      size_t startIndex = str.find_first_not_of(ChrsToTrim);
      if (startIndex == std::string::npos){str.erase(); return str;}
      str = str.substr(startIndex, str.size()-startIndex);
      str = str.substr(0, str.find_last_not_of(ChrsToTrim) + 1);
      return str;
}
0
 
LVL 30

Expert Comment

by:Axter
ID: 10736881
FYI:

The if statement in your original function is not making a comparison.
if(out.at(0), '\"') //This is using a comman operator instead of an equal

That should be using an equal sign instead.

if(out.at(0) == '\"')

To trim the right side.   You also want to take the inner if statement out side of the outer if statement.
Unless your intensions are to only remove the right quote if there is a left quote.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Accepted Solution

by:
mnashadka earned 100 total points
ID: 10736900
Here's a little function that would do the trick:

std::string StripQuotes(const std::string &str)
{
  if(str.length() >= 2 && *str.begin() == '"' && *str.rbegin() == '"') // If the length is at least 2 and the first and last character is a quote
    return str.substr(1, str.length() - 2); // Return the middle of it
  else
    return str; // Otherwise return the original
}

void main()
{
  string one = "\"Hello\"", two = "Whatever", three = "\"Stuff";
  one = StripQuotes(one); // Will give you Hello
  two = StripQuotes(two); // Will give you Whatever
  three = StripQuotes(three); // Will give you "Stuff
}
0
 
LVL 30

Expert Comment

by:Axter
ID: 10736908
Also in the original function the input parameter is passed in by value.  That means you don't need to assigned it to another variable within the function.

string StripQuotes(string in)
{
   string out = in; //This is not needed.

Instead just modify the input variable directly
string StripQuotes(string out)
{

In any case, I think the code I posted should work out better, but I wanted to make sure you knew some of the reasons why your original code wasn't working.
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10739589
Hi jpattee,

Use iterators:

#include <cctype>
#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

int isquote(int c){
    return c=='\"';
}

int main(){
     string quotyString="\"Wash your hands\", mom said.";
     cout << "With quotes: " << quotyString << endl;
     quotyString.erase(remove_if(quotyString.begin(), quotyString.end(),ptr_fun(::isquote)),quotyString.end());
     cout << "Without quotes: " << quotyString << endl;

}


Cheers,
Stefan
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10739602
jpattee,

If you want to do it the C way:

void strip_char(char* src,char stripwhat){
    char* dest=src;
    while(*src){
        while(*src == stripwhat) src++;
        *(dest++)=*(src++);
    }
    *dest=*src; /* Add trailing \0 */
}

Stefan
0
 

Author Comment

by:jpattee
ID: 10744951
I think I am trying to do strings one character at a time like they were arrays.
I need to adjust my thinking, and get more familiar with the string functions.

Thanks for all the solutions.

-jimp
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10755738
Yes, iterators are pretty useful (not only for strings), but have a steep learning curve...

Don't use C++ strings in the same way as you use them in C.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now