Search code examples
objective-cnsstringnsnumberfoundation

Get a char from NSString and convert to int


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

Solution

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