Reputation: 575
I am just starting off with Objective-C and iphone app dev, i'm trying to design a calculator app, the logic i have used is this : when the user clicks any button i take the title of the button by [sender titleForState:UIControlStateNormal] method and then go on appending it onto a string(NSString *result). say the user enters 123+456 , then in my string i will have "123+456", now i want two strings "123" and "456" so that i can add them by [result intValue] method.
So my question is, how do i get these two separate strings ("123" & "456")?
An example code with suitable methods would be very helpful.
Upvotes: 2
Views: 1959
Reputation: 6715
Found this at NSString tokenize in Objective-C
Found this at http://borkware.com/quickies/one?topic=NSString (useful link):
NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];
Hope this helps!
Adam
NSString *string = @"123+456";
NSArray *chunks = [string componentsSeparatedByString: @"+"];
int res = [[chunks objectAtIndex:0] intValue]+[[chunks objectAtIndex:1] intValue];
Upvotes: 2
Reputation: 57179
You can separate strings by using NSString
s componentsSeparatedByString:
NSString *calculation = @"1235+4362";
NSArray *results = [calculation componentsSeparatedByString:@"+"];
NSLog(@"Results: %@", results);
If you are attempting to implement a calculator you may want to familiarize yourself with Reverse Polish Notation and the Shunting-Yard Algorithm as you will find trying to create a simple calculator will be a bit more challenging than expected..
Upvotes: 1
Reputation: 3592
NSString * mystring = @"123+456";
NSArray * array = [mystring componentsSeparatedByString:@"+"];
NSString * str1 = [array objectAtIndex:0]; //123
NSString * str2 = [array objectAtIndex:1]; //456
Upvotes: 14
Reputation: 14662
NSArray* yourTwoStrings = [@"123+456" componentsSeparatedByString:@"+"];
Upvotes: 1