I think it's silly question but i dont know what to do with this.There are lots of order generated each order price string come in this format "123,145,开发者_开发问答234,33,8," this is for one order only can you please tell me how can i add all this value and get the sum of all like "123+145+234+33+8" = 543 .the sum i have to show into tableview for each order. i stuck on these please i develop this stuff for iphone please give me information with code.
Thank You. If the information is not complete let me know.
Split the string by ,
, convert to numbers and sum them up:
NSArray *parts = [myString componentsSeparatedByString:@","];
for (NSString *s in parts) {
sum += [s integerValue];
}
If your string always has an additional trailing ,
, you could e.g. trim it by using:
NSRange trimRange = NSMakeRange(0, [myString length]-1);
NSString *trimmed = [myString substringWithRange:trimRange];
... or by using -stringByTrimmingCharactersInSet:
if your needs are more complex.
A little modification to Georg Fritzsche's answer
NSMutableArray* array = [NSMutableArray arrayWithArray:[myString componentsSeparatedByString:@","]];
//// Remove last object. You might want to make sure it's always the case. ////
[array removeLastObject];
//// Here's a cool trick using Collection Operators. ////
NSNumber* sum = [array valueForKeyPath:@"@sum.intValue"];
NSInteger k = [sum intValue];
精彩评论