2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
wOlVeRiNe
  • 545
  • 1
  • 4
  • 21

4 Answers4

14
NSString * mystring = @"123+456";
NSArray * array = [mystring componentsSeparatedByString:@"+"];
NSString * str1 = [array objectAtIndex:0]; //123
NSString * str2 = [array objectAtIndex:1]; //456
Youssef
  • 3,582
  • 1
  • 21
  • 28
2

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];
Community
  • 1
  • 1
ymutlu
  • 6,585
  • 4
  • 35
  • 47
  • the "objectAtIndex" method was missing, but i think u expected me to figure that out :p, which ofcourse i couldn't as i'm just in the learning phase. Neway, i appreciate your taking valuable time out to think about an answer and also ofc for answering. Thanks. – wOlVeRiNe Sep 20 '11 at 16:09
1
NSArray* yourTwoStrings = [@"123+456" componentsSeparatedByString:@"+"];
gcamp
  • 14,622
  • 4
  • 54
  • 85
1

You can separate strings by using NSStrings 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..

Joe
  • 56,979
  • 9
  • 128
  • 135
  • Thanks a lot for the postfix and algo suggestion. But the thing is that i wanna do it without using any pushing-popping mechanism i.e a stack. If my efforts don't yield success, i'll definately go with the postfix method :), thanks – wOlVeRiNe Sep 20 '11 at 16:12