c++stringvectorc++98erase-remove-idiom

To remove double quotes from vector<string> c++ 98


I am trying to remove the double quotes characters from my vector string value.

for eg: if my vector string has values (50,40,"50GB","40GB",60). i am trying refine the vector by erasing Double quotes(" "). so the my final vector (50,40,50GB,40GB,60).

Below is the piece of code I tried to make it work, I got compilation issue saying... Please help me with fixing this issue and to achieve the desired result.

In function ‘void removeCharsFromVectorString(std::vector<std::basic_string<char> >&)’:
strErase.cpp:28:27: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
           if(str[p][i] == " \" ")

Code: 
    #include <iostream>
    #include <string.h>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    void removeCharsFromVectorString( vector<string> &str)
    {
       for(int p = 0; p < str.size(); p++)
       {
          for ( unsigned int i = 0; i < str[p].length() ; ++i )
          {
              if(str[p][i] == " \" ")
              {
                  str[p].erase(i, 1);
                  i--;
              }
              //str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
          }
       }
      for(int p = 0; p < str.size(); p++)
       {
          cout<<str[p]<<endl;
       }
    }
    
    int main()
    {
       vector<string> str; 
       str.push_back("50");
       str.push_back("40");
       str.push_back("\"50GB\"");
       str.push_back("\"40GB\"");
       str.push_back("60");
       removeCharsFromVectorString(str);
       return 0;
    }


Solution

  • str[p][i] is of type char, so you need to compare it to a char. Putting your double quote in two single quotes should do the trick:

    if(str[p][i] == '"')
    {
        str[p].erase(i, 1);
        i--;
     }
    

    Full code:

    #include <iostream>
    #include <string.h>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    void removeCharsFromVectorString( vector<string> &str)
    {
        for(int p = 0; p < str.size(); p++)
        {
            for ( unsigned int i = 0; i < str[p].length() ; ++i )
            {
                if(str[p][i] == '"')
                {
                    str[p].erase(i, 1);
                    i--;
                }
                //str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
            }
        }
        for(int p = 0; p < str.size(); p++)
        {
            cout<<str[p]<<endl;
        }
    }
    
    int main()
    {
        vector<string> str; 
        str.push_back("50");
        str.push_back("40");
        str.push_back("\"50GB\"");
        str.push_back("\"40GB\"");
        str.push_back("60");
        removeCharsFromVectorString(str);
        return 0;
    }
    

    Output:

    50 40 50GB 40GB 60