Best way to remove leading zeros from QString

What do you guys / gala think is the best way to remove leading zeros from a QString?

I am dealing with numbers like:

099900000002 008800000031 88800000043 

Do I need to iterate over each character one at a time, or is there a more elegant way to use the QString :: replace () function, which I did not think about?

+4
source share
6 answers

Remove any number of zeros from the beginning of the line:

 myString.remove( QRegExp("^[0]*") ); 
+8
source

I looked at the QString doc and there is not one that will be simple and so far explicit 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); } 
+5
source

I am not familiar with QStrings, so I base this on std :: string. Perhaps you can just convert?

If you can use boost, you can do something like:

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

If by elegance you mean not repeating yourself, then the fact that Qt containers are largely compatible with STL algorithms can be useful (but not necessarily 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 better work, as suggested by UmNyobe, which is faster and more understandable.

+1
source

Here is an elegant single line that does not use regex:

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

Not the fastest, but much faster than the regular expression version. Also, if you have C ++ 11, you can do something like this:

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

It's very fast.

0
source

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

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

Source: https://habr.com/ru/post/1389677/


All Articles