5
votes

What do you guys/gals think would be the best way to remove leading zeros from a QString?

I am dealing with numbers like:

099900000002
008800000031
88800000043

Do I have to iterate over every character, one at a time, or is there a more elegant way using the QString::replace() function that I haven't thought of?

7
You will have to iterate through the string, directly or indirectly.Stephen Chu

7 Answers

13
votes

Remove any number of zeros from the beginning of a string:

myString.remove( QRegExp("^[0]*") );
5
votes

I looked at the QString doc and there is none which will be simple and while being explicit of what you want to do. Just write like this

void removeLeadingzeros(QString &s){

 int i = 0;
 while(i < s.length() && s[i]=='0'){
  i++;
 }

 s.remove(0,i);
}
1
votes

I am not familiar with QStrings, so I am basing this off std::string. Perhaps you can convert pretty simply?

If you can use boost then you could do something like:

std::string s("000003000000300");
boost::trim_left_if( s, boost::is_any_of("0") );
1
votes

If by elegant you mean not iterating yourself, then the fact Qt containers are largely compatible with STL algorithms may be helpful (but not necessary efficient):

QString::iterator n = std::find_if(myQString.begin(), myQString.end(), std::bind2nd(std::not_equal_to<QChar>(), '0'));
myQString.remove(0, n-myQString.begin());

Fancy. But you'd stlll better off iterate yourself as UmNyobe suggested, which is faster and clearer.

1
votes

Here is an elegant one-liner that doesn't use regex:

while (s.startsWith('0')) { s.remove(0,1); }

Not the fastest, but it is significantly faster than the regex version. Also, if you have C++11, you could do something like this:

s.remove(0,
         std::distance(s.begin(),
                       std::find_if_not(s.begin(), s.end(),
                                        [](QChar c) { return c == '0'; } )));

Which is very fast.

1
votes

QString mystring = "00000545465651";

mystring = QString::number(mystring.toInt());

// Result = mystring = "545465651";

By converting the QString to an Integer the leading zeros will be removed. Than u just convert it back to a QString.

0
votes

Assuming myString is a number, or you can find out by checking if ok is true

bool ok = false;
QString::number(myString.toLongLong(&ok));