Removing leading zeroes from a string

Viewed 17835

I have a string 0023525631 but what I want is the string 23525631 -- without the leading zeroes. How do I do this?

9 Answers

When in doubt, iterate

No need to get as complex as other answers.

Something as simple as this shall suffice.

while ([string hasPrefix:@"0"]) {
    string = [string substringFromIndex:1];
}

Notes:

•If your string's number is something like 0.12 you will be left with .12. If undesired, then simply check if hasPrefix:@"." and concatenate with a prepending @"0".

•If your string's number is just 0 you will be left with nothing. If undesired, then simply check if isEqualToString:@"" and set to @"0"

•If speed is really really important to you, you could iterate through the characters (scan) and break; upon reaching a non-zero value (at index n), then you'd simply substringFromIndex:n

Related