Reputation: 1335
I'm checking is first letter of string is 0, if it is remove it and call again method to check is there is still 0. I've debugged this and it seems like when it accomplish number without 0, it goes backwards. Code:
-(NSString *)deleteZerosOnFirst:(NSString *)card
{
NSString *firstLetter = [card substringToIndex:1];
if ([firstLetter isEqualToString:@"0"]) {
card = [card substringFromIndex:1];
[self deleteZerosOnFirst:card];
NSLog(@"CARD: %@", card);
return card;
}
else {
NSLog(@"CARD: %@", card);
return card;
}
}
Upvotes: 0
Views: 1507
Reputation: 385700
Here's your recursive call:
[self deleteZerosOnFirst:card];
That doesn't modify the string that card
references. It creates and returns a new string. You're ignoring the returned string. You want this:
card = [self deleteZerosOnFirst:card];
But this is really a lot simpler:
@implementation NSString (withoutLeadingZeroes)
- (NSString *)withoutLeadingZeroes {
NSString *s = self;
while ([s hasPrefix:@"0"]) {
s = [s substringFromIndex:1];
}
return s;
}
@end
Upvotes: 3
Reputation: 14157
The main problem is that you're not using the result of the recursion. The line of code where you call yourself should say this:
card = [self deleteZerosOnFirst:card];
Also, you're calling deleteZerosOnFirst before you do the NSLog. Reverse the order of these two lines. That will at least give you your debug output in the right sequence.
Upvotes: 4