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

问题描述 投票:1回答:3

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

intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());

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

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

[NSNumber numberWithChar:[intS characterAtIndex:(i)]]
objective-c nsstring nsnumber foundation
3个回答
13
投票

这里有许多有趣的建议。

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

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);

4
投票

它没有明确地必须是char。这是一种做法:)

NSString *test = @"12345";
NSString *number = [test substringToIndex:1];
int num = [number intValue];

NSLog(@"%d", num);

1
投票

只是为了提供第三种选择,您也可以使用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
}
© www.soinside.com 2019 - 2024. All rights reserved.