Add 1 to a number in an NSString that contains characters Objective-C

Viewed 49

I am new to learning Objective-C (my first programming language!) and trying to write a little program that will add 1 to a number contained within a string. E.g. AA1BB becomes AA2BB. .

So far I have tried to extract the number and add 1. Then extract the letters and add everything back together in a new string. I have had some success but can't manage to get back to the original arrangement of the initial string.

The code I have so far gives a result of 2BB and disregards the characters before the number which is not what I am after (the result I am trying for with this example would be AA2BB). I can't figure out why!

NSString* aString = @"AA1BB";

NSCharacterSet *numberCharset = [NSCharacterSet characterSetWithCharactersInString:@"0123456789-"]; //Creating a set of Characters object//

NSScanner *theScanner = [NSScanner scannerWithString:aString];

int someNumbers = 0;

while (![theScanner isAtEnd]) {
  // Remove Letters
  [theScanner scanUpToCharactersFromSet:numberCharset
                             intoString:NULL]; 
  if ([theScanner scanInt:&someNumbers]) {}
}

NSCharacterSet *letterCharset = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];

NSScanner *letterScanner = [NSScanner scannerWithString:aString];

NSString* someLetters;
while (![letterScanner isAtEnd]) {
     // Remove numbers
     [letterScanner scanUpToCharactersFromSet:letterCharset
                                intoString:NULL];

   if ([letterScanner scanCharactersFromSet:letterCharset intoString:&someLetters]) {}
}

++someNumbers; //adds +1 to the Number//


NSString *newString = [[NSString alloc]initWithFormat:@"%i%@", someNumbers, someLetters]; 

NSLog (@"String is now %@", newString);
1 Answers

This is an alternative solution with Regular Expression.

It finds the range of the integer (\\d+ is one or more digits), extracts it, increments it and replaces the value at the given range.

NSString* aString = @"AA1BB";
NSRange range = [aString rangeOfString:@"\\d+" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
    NSInteger numericValue = [aString substringWithRange:range].integerValue;
    numericValue++;
    aString = [aString stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%ld", numericValue]];

}
NSLog(@"%@", aString);
Related