• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2126
  • Last Modified:

How do I subtract two strings in objective-c?

NSString * = @"158";
NSString * = @"23";

how do I get the result of string 158 subtracting 23 as a string?
0
charmingduck
Asked:
charmingduck
  • 2
  • 2
2 Solutions
 
Hamidreza VakilianSenior iOS DeveloperCommented:
        NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
        
        int number1 = [[formatter numberFromString:@"158"] intValue];
        int number2 = [[formatter numberFromString:@"23"] intValue];
        
        NSString* result = [NSString stringWithFormat:@"%d", number1 - number2];

Open in new window

1
 
charmingduckAuthor Commented:
do you mind explaining each line for me, since it is not much code here.   )
0
 
Hamidreza VakilianSenior iOS DeveloperCommented:
To convert a NSString to int we should declare an instance of class NSNumberFormatter. So consider formatter as our converter.
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];

Open in new window



Here we told our so called converter, formatter that we want to convert numbers which are decimal (not float e.g.)
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

Open in new window



[formatter numberFromString:@"158"] converts string @"158" to a NSNumber object which contains decimal 158. But we want a simple int here so we tell the NSNumber to return the int value and we store them in number1 and number2.
int number1 = [[formatter numberFromString:@"158"] intValue];
        int number2 = [[formatter numberFromString:@"23"] intValue];

Open in new window



Now we can subtract the two ints easily but we also want to convert the result int into NSString; thats why we use stringWithFormat:@"%d". (%d refers to int)
NSString* result = [NSString stringWithFormat:@"%d", number1 - number2];

Open in new window

0
 
charmingduckAuthor Commented:
Dude, I love you so much!!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now