trim 0s

N

Netocrat

(e-mail address removed) wrote:
Zara wrote:
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a
string, e.g., I'd like to take a string like 00000012 and convert
it to 12.

char *s_ini="00000012";
char *s_final=s_ini;
while (*s_final=='0') s_final++;

Almost ... oh what the hell, might as well do it right:

for (i = 0; s_ini == '0'; i++) if (s_ini == '\0' && i > 0) {
i--;
break;
}

s_final = &s_ini;
[...]
I suspect you are going to say that you think "0000" with leading zeroes
removed is "0", and you also planned to write a program that gives "0",
but you accidentally wrote a program that gives "".


If so it's easily fixed and the result isn't obscure:

for (i = 0; s_ini == '0'; i++) ;
if (s_ini == '\0' && i > 0)
i--;
s_final = &s_ini;

The specification isn't clear enough to decide on correctness, but this
seems like more useful semantics when dealing solely with numeric strings
that must later be displayed as integers.
 
W

websnarf

S.Tobias said:
Who said anything about numbers? The OP only wanted to remove
all initial zeroes from a string. :)
http://dspace.dial.pipex.com/town/green/gfd34/art/bloopers.html
"This is a lovely picture ..." is very adequate here.

Seriously, I'm sure the OP has already discovered by now
what he really needed.

If you think that sort of bug tends to eventually get sorted out in
serious applications try the following:

printf ("%f\n", 0);

.... in Microsoft Visual Studio 2003. This is the result I got:

86191978822782173000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

I wish I were kidding (it prints out other numbers just fine).
 
W

websnarf

If you think that sort of bug tends to eventually get sorted out in
serious applications try the following:

printf ("%f\n", 0);

... in Microsoft Visual Studio 2003. This is the result I got:

86191978822782173000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

I wish I were kidding (it prints out other numbers just fine).

Nevermind ... I just caught what I did wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

trim 6
how to trim() a String only at the right side? 11
trim whitespace v3 170
Tasks 1
Why does 1 represent a negative sign bit? 0
Converting an Array to a String in JavaScript 7
Trim string 42
DecimalFormat 7

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,192
Latest member
KalaReid2

Latest Threads

Top