Reputation: 14408
I have a string like "00Welcome", "0000To", "0STACKOVERFLOW", "NOW".
Given a NSString, how can i remove zeros from prefix.
I thought initially to go with CharacterAIndex, but looks like not a good idea.
I have just gone through the below link:
Most efficient way to iterate over all the chars in an NSString
Upvotes: 1
Views: 307
Reputation: 512
NSString *str =@"000034234247236000049327428900000";
NSRange range = [str rangeOfString:@"^0*" options:NSRegularExpressionSearch];
str= [str stringByReplacingCharactersInRange:range withString:@""];
Try this alternative use of regular expressions given by @dreamlax
Upvotes: 3
Reputation: 95335
This will remove all 0s from both then beginning and the end using stringByTrimmingCharactersInSet:
:
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"0"];
NSString *input = @"00Welcome";
NSString *output = [input stringByTrimmingCharactersInSet:charsToTrim];
Using regular expressions:
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"^0+"];
NSString *input = @"00Welcome";
NSString *output = [re stringByReplacingMatchesInString:input
options:0
range:NSMakeRange(0, [input length])
withTemplate:@""];
Upvotes: 3
Reputation: 52538
If the zeroes are rare:
while ([myString hasPrefix:@"0"])
myString = [myString subStringFromIndex:1];
Upvotes: 3