1

I have a NSString like @"05205" or @"05931" or so. I want to remove the leading 0 characters.

E.g. @"05205" in @"5205" or @"00072" in @"72".

How can I achieve this in Objective-C?

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Loko
  • 185
  • 3
  • 12

2 Answers2

7

With the NSStringCompareOptions NSAnchoredSearch, the search is limited to the start of the string, so you can use stringByReplacingOccurrencesOfString:withString:options:range: this way:

NSString* str= @"0072";
str= [str stringByReplacingOccurrencesOfString:@"0"
                                    withString:@""
                                       options:NSAnchoredSearch
                                         range:NSMakeRange(0, str.length)];
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
6

If you convert the string to an integer and then back to a string, it will trim the leading zeros.

NSString *s = @"0072";
NSString *newString =[ NSString stringWithFormat:@"%d",[s integerValue]];
rdelmar
  • 103,982
  • 12
  • 207
  • 218