Whoami
Whoami

Reputation: 14408

How can i remove prefixed zeros from NSString

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

Answers (3)

vishnuvarthan
vishnuvarthan

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

dreamlax
dreamlax

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

gnasher729
gnasher729

Reputation: 52538

If the zeroes are rare:

while ([myString hasPrefix:@"0"])
    myString = [myString subStringFromIndex:1];

Upvotes: 3

Related Questions