在 C# 中,我可以通过以下方式将字符串中的任何字符转换为整数
intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());
Objective-C 中这段代码的最短等价物是什么?
我见过的最短的一行代码是
[NSNumber numberWithChar:[intS characterAtIndex:(i)]]
在 C# 中,我可以通过以下方式将字符串中的任何字符转换为整数
intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());
Objective-C 中这段代码的最短等价物是什么?
我见过的最短的一行代码是
[NSNumber numberWithChar:[intS characterAtIndex:(i)]]
许多有趣的建议,在这里。
这就是我认为最接近原始代码段的实现:
NSString *string = @"123123";
NSUInteger i = 3;
NSString *singleCharSubstring = [string substringWithRange:NSMakeRange(i, 1)];
NSInteger result = [singleCharSubstring integerValue];
NSLog(@"Result: %ld", (long)result);
自然,获得你想要的东西的方法不止一种。
但是,正如您自己注意到的那样,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);
它不必明确地是一个char
. 这是一种方法:)
NSString *test = @"12345";
NSString *number = [test substringToIndex:1];
int num = [number intValue];
NSLog(@"%d", num);
只是为了提供第三种选择,您也可以使用NSScanner:
NSString *string = @"12345";
NSScanner *scanner = [NSScanner scannerWithString:string];
int result = 0;
if ([scanner scanInt:&result]) {
NSLog(@"String contains %i", result);
} else {
// Unable to scan an integer from the string
}