2012-04-09 90 views
0

我想字符转换为基于预定值的整数,例如:基于值数组将NSString转换为NSInteger的最佳方式是什么?

a = 0 
b = 1 
c = 2 
d = 3 

等等

现在,我有做一个的if/else如果,我只是想知道我应该做的更快/更好的方式,因为转换列表可能会相当长。

下面是我使用的是什么现在:

-(NSInteger)ConvertToInt:(NSString *)thestring { 
    NSInteger theint; 
    if([thestring isEqualToString:@"a"] == YES){ 
     theint = 0; 
    } else if ([thestring isEqualToString:@"b"] == YES){ 
     theint = 1; 
    } //etc... 

    return theint; 
} 

这工作得很好,但正如我所说,如果它更有意义我可以创建一个数组的所有键/值,然后仅仅通过运行返回整数?

请提供示例,因为我是Objective C/iOS的初学者。我来自Web语言。

谢谢!

编辑:谢谢大家的帮助。我用taskinoors回答,但我换成这是给这个错误信息的NSDictionary:

NSDictionary *dict; 
dict = [NSDictionary dictionaryWithObjectsAndKeys: 
     [NSNumber numberWithInt:0], @"a", 
     [NSNumber numberWithInt:1], @"b", 
     [NSNumber numberWithInt:2], @"c", nil]; 

回答

4
unichar ch = [thestring characterAtIndex:0]; 
theint = ch - 'a'; 

需要注意的是,'a'用单引号字符是a,不串"a"

如果这些值与您的示例不一样,那么您可以将所有预定义的值存储到字典中。例如:

"a" = 5; 
"b" = 1; 
"c" = 102; 

NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithInt:5], 
    [NSNumber numberWithInt:1], [NSNumber numberWithInt:102], nil]; 
NSArray *keys = [NSArray arrayWithObjects:@"a", @"b", @"c", nil]; 
NSDictionary *dic = [NSDictionary dictionaryWithObjects:values forKeys:keys]; 

theint = [[dic valueForKey:thestring] intValue]; 
+0

对不起,我不太确定该怎么做。你能告诉我如何使它成为一个函数,我可以传递字符串“a”并返回一个整数。感谢您的意见。 – tsdexter 2012-04-09 19:48:14

+0

我需要使用字符串,因为我也会有值,例如“ab”传入,这将需要返回一个整数。 – tsdexter 2012-04-09 19:50:31

+0

@tsdexter如果你不明白这个例子,你应该更好地学习Objective-C和C. – 2012-04-09 19:50:31

1

如果你想保持一定的灵活性,在什么字符串映射到什么整数,和你的整数从0到n-1运行,你有n个独特的项目在数组中,你可以做类似这样的:

-(NSInteger)ConvertToInt:(NSString *)thestring { 
    NSArray *arr = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d", nil]; 
    NSInteger theint = [arr indexOfObject:thestring]; 
    return theint; 
} 

现在这每一次,这将是非常低效的将建立数组,最佳的方法是在你的班上一旦建立数组,然后只使用一个参考该阵列与indexOfObject方法调用。

+0

谢谢。这看起来不错。然而,虽然我可以按数字顺序填充数组,但是最好为每个数组项目分配整数,因为某些情况下整数将不会按顺序排列,或者不会有相应的字符串,因此我必须将它们放在哑元缺失整数的数据。对我来说,按照我的数据顺序填充数组也是更容易的(整数不按顺序)。任何关于如何去做的建议? – tsdexter 2012-04-09 19:55:25

+0

我认为他的意图是建立一种密码,他可以在那里传递一个像“aryls”这样的字符串,并得到1,18,25,14,19。这是正确的@tsdexter? – anthropomorphic 2012-04-09 19:55:33

+0

在这种情况下,您会想要像上面提到的@taskinoor一样使用NSDictionary。 – 2012-04-09 20:01:56

相关问题