This is actually a case that is perfectly suited for regular expressions:
NSString *str = @"00000123";
NSString *cleaned = [str stringByReplacingOccurrencesOfString:@"^0+"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
Only one line of code (in a logical sense, line breaks added for clarity) and there are no limits on the number of characters it handles.
A brief explanation of the regular expression pattern:
The ^
means that the pattern should be anchored to the beginning of the string. We need that to ensure it doesn't match legitimate zeroes inside the sequence of digits.
The 0+
part means that it should match one or more zeroes.
Put together, it matches a sequence of one or more zeroes at the beginning of the string, then replaces that with an empty string - i.e., it deletes the leading zeroes.