从NSString获取一个char并转换为int

TOP*_*KEK 1 objective-c nsnumber nsstring foundation

在C#中,我可以通过以下方式将我的字符串中的任何字符转换为整数

intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());
Run Code Online (Sandbox Code Playgroud)

Objective-C中此代码的最短等价物是什么?

我见过的最短的一行代码是

[NSNumber numberWithChar:[intS characterAtIndex:(i)]]
Run Code Online (Sandbox Code Playgroud)

Mon*_*olo 13

这里有许多有趣的建议.

这是我认为产生最接近原始代码段的实现:

NSString *string = @"123123";
NSUInteger i = 3;
NSString *singleCharSubstring = [string substringWithRange:NSMakeRange(i, 1)];
NSInteger result = [singleCharSubstring integerValue];
NSLog(@"Result: %ld", (long)result);
Run Code Online (Sandbox Code Playgroud)

当然,获得你所追求的东西的方法不止一种.

但是,正如您自己注意到的那样,Objective-C有其缺点.其中之一就是它不会尝试复制C功能,原因很简单,因为Objective-C已经 C.所以也许你最好只做你想要的简单C:

NSString *string = @"123123";

char *cstring = [string UTF8String];
int i = 3;
int result = cstring[i] - '0';
NSLog(@"Result: %d", result);
Run Code Online (Sandbox Code Playgroud)