Objective-C 将 '00120' 之类的字符串转换为整数数组

标签 objective-c ios

我需要将像 '00120' 这样的字符串转换为 NSIntegers 的 NSArray。

你能帮忙吗?

谢谢

最佳答案

试试这段代码:

NSString *input = @"00120";
NSMutableArray *integers = [NSMutableArray array];

for (int i = 0; i < input.length; i++) {
    unichar c = [input characterAtIndex:i];

    if (!isnumber(c))
        [integers addObject:[NSNumber numberWithInt:-1]];
    else 
        [integers addObject:[NSNumber numberWithInt:c - '0']]; // convert the ASCII value to it's integer counterpart.
}

当然,这是假设您的所有字符都是字符串中的数字。

编辑:如果你想要一个 NSInteger,你需要制作一个 C 数组:

NSString *input = @"00120";
NSInteger *integers = calloc(input.length, sizeof(NSInteger));
NSInteger integersLen = input.length;

for (int i = 0; i < input.length; i++)
{
    unichar c = [input characterAtIndex:i];

    if (!isnumber(c))
        integers[i] = -1;
    else
        integers[i] = c - '0'; // convert the ASCII value to it's integer counterpart
}

关于Objective-C 将 '00120' 之类的字符串转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9583819/

相关文章:

ios - 以编程方式隐藏 Apple iAd ADBannerView

iphone - 更新应用程序时是否有可能更改目录?

ios - MKAnnotationView 自定义按钮图片

ios - 在推送/本地通知的右侧显示自定义图像?

objective-c - 以编程方式将 NSButton 实例添加到 NSWindow

ios - 如何使用uiviewcontroller实现滑出式菜单?

iOS SQLite 数据库...预填充数据

ios - Travis-CI 错误为 "eval pod install"

ios - 旋转 Mapbox 相机

ios - PFObject 没有成员名称 'subscript'