C# では、次の方法で任意の char を文字列から整数に変換できます
intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());
Objective-C でこのコードに相当する最短のものは何ですか?
私が見た中で最も短い1行のコードは
[NSNumber numberWithChar:[intS characterAtIndex:(i)]]
C# では、次の方法で任意の char を文字列から整数に変換できます
intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());
Objective-C でこのコードに相当する最短のものは何ですか?
私が見た中で最も短い1行のコードは
[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 には欠点があります。それらの 1 つは、Objective-C が既に C であるという単純な理由から、C の機能を複製しようとしないことです。したがって、単純な C でやりたいことだけを行う方がよいでしょう。
NSString *string = @"123123";
char *cstring = [string UTF8String];
int i = 3;
int result = cstring[i] - '0';
NSLog(@"Result: %d", result);
明示的に である必要はありませんchar
。これがそれを行う1つの方法です:)
NSString *test = @"12345";
NSString *number = [test substringToIndex:1];
int num = [number intValue];
NSLog(@"%d", num);
3 番目のオプションを提供するために、これにも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
}