Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading zeros from string using C++?

Tags:

c++

string

I want to remove leading zeroes from string like "0000000057".

I did like this but didn't get any result:

string AccProcPeriNum = strCustData.substr(pos, 13);

string p48Z03 = AccProcPeriNum.substr(3, 10);

I want output only 57.

Any idea in C++?

like image 535
samio peter Avatar asked Sep 08 '14 14:09

samio peter


2 Answers

#include <string>    

std::string str = "0000000057";
str.erase(0, str.find_first_not_of('0'));

assert(str == "57");

LIVE DEMO

like image 58
Piotr Skotnicki Avatar answered Sep 27 '22 00:09

Piotr Skotnicki


Piotr S's answer is good but there is one case it will return the wrong answer, that is the all-zero case:

000000000000

To consider this in, use:

str.erase(0, min(str.find_first_not_of('0'), str.size()-1));

Even when str.size() will be 0, it will also work.

like image 36
intijk Avatar answered Sep 27 '22 00:09

intijk