Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove leading zeros from a QString

Tags:

c++

qt

qt4

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?

like image 463
Wes Avatar asked Jan 06 '12 15:01

Wes


People also ask

How do I remove zeros from the beginning of a string?

The simplest approach to solve the problem is to traverse the string up to the first non-zero character present in the string and store the remaining string starting from that index as the answer. If the entire string is traversed, it means all the characters in the string are '0'.

How do you remove leading zeros from an array?

Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container.

How do you remove leading zeros in Robot Framework?

Input : ${number}= 0000123 Output Should be : 123 @{random} = ['00123','3456'] @{random}[0] will have 00123 @{random}[0] should be equal to 123 (How to strip leading zero's ?)

How do you remove zeros in front of a number in C++?

stoi() function in C++ is used to convert the given string into an integer value. It takes a string as an argument and returns its value in integer form. We can simply use this method to convert our string to an integer value which will remove the leading zeros.


2 Answers

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

myString.remove( QRegExp("^[0]*") );
like image 189
Chris Avatar answered Sep 30 '22 04:09

Chris


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);
}
like image 22
UmNyobe Avatar answered Sep 30 '22 04:09

UmNyobe