如何将数字字符串从 'complex' 字符串转换为整数?

How do I convert string of numbers to ints from 'complex' string?

我当然熟悉将简单字符串转换为 int 的单行代码,即:

NSString *aString = @"56";
int value = [aString intValue];

但是,我将如何从包含各种值的复杂字符串的内容中提取单独的整数,例如:

NSString *testString = @"26 8 102 65 53 2 190 784 212";

我搜索了 Whosebug 和其他地方,但没有找到这个特定问题的答案。我想到了类似的东西:

int i, length;
NSString *testString = @"26 8 102 65 53 2 190 784 212";
length = [testString length];
for(i = 0; i < length; i++)
    {
    // do magic here…
    // int value = 26 (the first number in string);
    // rinse and repeat until last number (212) converted to int…
    }

但是我在这里超出了我的深度,这个伪代码当然失败了。谁能帮我解决乍一看似乎很简单的问题吗?

这是基于您之前代码的代码片段。

    NSString *testString = @"26 8 102 65 53 2 190 784 212";

    NSArray *testArray = [testString componentsSeparatedByString:@" "];

    for(NSString *numString in testArray)
    {
        int value = [numString intValue];

        NSLog(@"integer value: %i", value);
    }

输出

2019-07-17 10:58:45.460986-0700 ProxyTest[2337:109309] integer value: 26
2019-07-17 10:58:45.461066-0700 ProxyTest[2337:109309] integer value: 8
2019-07-17 10:58:45.461140-0700 ProxyTest[2337:109309] integer value: 102
2019-07-17 10:58:45.461222-0700 ProxyTest[2337:109309] integer value: 65
2019-07-17 10:58:45.461311-0700 ProxyTest[2337:109309] integer value: 53
2019-07-17 10:58:45.461385-0700 ProxyTest[2337:109309] integer value: 2
2019-07-17 10:58:45.461448-0700 ProxyTest[2337:109309] integer value: 190
2019-07-17 10:58:45.461510-0700 ProxyTest[2337:109309] integer value: 784
2019-07-17 10:58:45.461563-0700 ProxyTest[2337:109309] integer value: 212

我喜欢 NSScanner:

NSString* testString = @"26 8 102 65 53 2 190 784 212";
NSScanner* scan = [NSScanner scannerWithString: testString];
while (![scan isAtEnd]) {
    [scan scanUpToCharactersFromSet:
        [NSCharacterSet alphanumericCharacterSet] intoString:nil];
    int i;
    [scan scanInt:&i];
    NSLog(@"%d",i);
}

输出:

2019-07-17 11:17:06.219506-0700 MyApp[1675:114852] 26
2019-07-17 11:17:06.219639-0700 MyApp[1675:114852] 8
2019-07-17 11:17:06.219743-0700 MyApp[1675:114852] 102
2019-07-17 11:17:06.219885-0700 MyApp[1675:114852] 65
2019-07-17 11:17:06.220024-0700 MyApp[1675:114852] 53
2019-07-17 11:17:06.220150-0700 MyApp[1675:114852] 2
2019-07-17 11:17:06.220286-0700 MyApp[1675:114852] 190
2019-07-17 11:17:06.220413-0700 MyApp[1675:114852] 784
2019-07-17 11:17:06.220518-0700 MyApp[1675:114852] 212

收集整数留作 reader 的练习。