如何在iPhone应用程序中将NSString转换为NSInteger?

时间:2012-03-09 12:37:21

标签: objective-c ios nsstring

NSString * addString=[arrayyyy componentsJoinedByString:@","];

NSLog(@"add string is: %@",addString);// result is: 45,1

现在我想将上面的字符串转换为整数。

我试过这个:

NSInteger myInt=[addString intValue]; 
//NSLog(@"myInt is: %d",myInt);// result is: 45

3 个答案:

答案 0 :(得分:2)

如果你期望45.1,那么有两件事是错的:

  1. 45.1不是integer。您必须使用floatValue来读取值。

  2. 45,1(注意逗号)不是有效的浮点数。虽然45,1在某些区域设置中有效(即法语为1 000,25而不是1,000.25),但在阅读floatValue之前,您必须使用NSNumberFormatter转换字符串}。

  3. // Can't compile and verify this right now, so please bear with me.
    NSString *str = @"45,1";
    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
    NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease]; // lets say French from France
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setLocale:locale];
    float value = [[formatter numberFromString:str] floatValue];   // value = 45.1
    

答案 1 :(得分:0)

通过阅读这个问题,我想我可能会理解你想要的东西。

起点似乎是:

NSLog(@"add string is: %@",addString);// result is: 45,1

目前的结局是:

NSLog(@"myInt is: %d",myInt);// result is: 45

但似乎你仍然要打印45,1

我对此的猜测是你有一个名为arrayyyy的2个字符串[@“45”,@“1”]的数组,你想要将这两个值打印成整数。如果是这样,那么我认为你想要的是:

NSInteger myInt1 = [[arrayyyy objectAtIndex:0] intValue];
NSInteger myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(@"add string is: %d,%d",myInt1,myInt2);

注意如果数组中至少有两个字符串,则会因NSRangeException而崩溃。所以至少应该这样做:

NSInteger myInt1 = -1;
NSInteger myInt2 = -1;
if ([arrayyyy length] >0) myInt1 = [[arrayyyy objectAtIndex:0] intValue];
if ([arrayyyy length] >1) myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(@"add string is: %d,%d",myInt1,myInt2);

但即便如此,因为它假设-1的保护值不会出现在实际数据中。

答案 2 :(得分:0)

试用也适用于数学符号的NSExpression(例如+-/*):

NSNumber *numberValue = [[NSExpression expressionWithFormat:inputString] expressionValueWithObject:nil context:nil];

// do something with numberValue
相关问题