从 NSString 获取一个字符并转换为 int [英] Get a char from NSString and convert to int

查看:61
本文介绍了从 NSString 获取一个字符并转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

这里有许多有趣的建议.

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.

然而,正如您所注意到的,Objective-C 有其缺点.其中之一是它不会尝试复制 C 功能,原因很简单,Objective-C 已经 C.所以也许你最好在普通 C 中做你想做的事:

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

这篇关于从 NSString 获取一个字符并转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆