Click to See Complete Forum and Search --> : Best way to do this


Technocrat
April 3rd, 2003, 06:05 PM
Is there a better way to remove the perceding 0's in a STL string?

for example 00000343203 = 343203

I have tried std::find but that took out all zeros which isnt what I want. Whats the best code for this?

Philip Nicoletti
April 3rd, 2003, 06:22 PM
string str = ("00000343203");

string::size_type pos = str.find_first_not_of("0");

if (pos !=string::npos)
str.erase(0,pos);

Technocrat
April 3rd, 2003, 06:30 PM
Thanks I knew there had to be an easier way.

Ok now what if I wanted to change the 0's to spaces instead of erasing them so the alignment stays?

Philip Nicoletti
April 3rd, 2003, 07:05 PM
First, my previous post did not handle the case of all zeroes
correctly (i.e. str = "0000"). Here is a correction for this:


string str = ("0000");

if (!str.empty())
{
string::size_type pos = str.find_first_not_of("0");

if (pos !=string::npos)
str.erase(0,pos);
else
str = "0";
}


As for you next request, I think this does it.
I feel there must be a better way. (stringstream ??)
If I get time I will look into that.


string str = ("0012304");

if (!str.empty())
{
string::size_type pos = str.find_first_not_of("0");

if (pos !=string::npos)
str.replace(0,pos,pos,' ');
else
{
int n = str.size();
str.replace(str.begin(),str.end()-1,n-1,' ');
}
}

Philip Nicoletti
April 3rd, 2003, 08:33 PM
You can create functions for these types of tasks,
and they can be made a little more general. See
the following example (cout in functions for
illustrative(sp?) purposes use only) :


#include <iostream>
#include <string>

using namespace std;

void RemoveLeading(std::string& str, const char* chars2remove)
{
cout << "|" << str << "|" << endl;
if (!str.empty())
{
string::size_type pos = str.find_first_not_of(chars2remove);

if (pos !=string::npos)
str.erase(0,pos);
else
str = str[str.size()-1]; // ?????
}
cout << "|" << str << "|" << endl << endl;
}

void ReplaceLeading(std::string& str, const char* chars2replace, char c)
{
cout << "|" << str << "|" << endl;
if (!str.empty())
{
string::size_type pos = str.find_first_not_of(chars2replace);

if (pos !=string::npos)
str.replace(0,pos,pos,c);
else
{
int n = str.size();
str.replace(str.begin(),str.end()-1,n-1,c);
}
}
cout << "|" << str << "|" << endl << endl;
}


int main()
{
string str;

str = "0000000";
RemoveLeading(str,"0"); // remove leading zeroes

str = " 123";
RemoveLeading(str," "); // remove leading blanks

str = " 001234";
RemoveLeading(str," 0"); // remove leading zeroes and blanks

str = "00012340";
ReplaceLeading(str,"0",' '); // replace leading zeroes with blanks

str = " 12340";
ReplaceLeading(str," ",'0'); // replace leading blanks with zeroes

str = " 012340";
ReplaceLeading(str,"0 ",'*'); // replace leading zeroes and blanks with *

return 0;
}

Technocrat
April 4th, 2003, 10:46 AM
Thank you SO much!!