Get a char from NSString and convert to int

╄→尐↘猪︶ㄣ 提交于 2019-12-11 07:45:23

问题


In C# I can convert any char from my string to integer in the following manner

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

What is the shortest equivalent of this code in Objective-C ?

The shortest one line code I've seen is

[NSNumber numberWithChar:[intS characterAtIndex:(i)]]

回答1:


Many interesting proposals, here.

This is what I believe yields the implementation closest to your original snippet:

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

Naturally, there is more than one way to obtain what you are after.

However, As you notice yourself, Objective-C has its shortcomings. One of them is that it does not try to replicate C functionality, for the simple reason that Objective-C already is C. So maybe you'd be better off just doing what you want in plain C:

NSString *string = @"123123";

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



回答2:


It doesn't explicitly have to be a char. Here is one way of doing it :)

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

NSLog(@"%d", num);



回答3:


Just to provide a third option, you can use NSScanner for this too:

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
}


来源:https://stackoverflow.com/questions/11193611/get-a-char-from-nsstring-and-convert-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!