Solved

STL string function to strip quotes

Posted on 2004-04-01
11
1,320 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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
 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

821 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