我很熟悉将简单的字符串转换为int的单行代码,即:
NSString *aString = @"56";
int value = [aString intValue];
但是,我将如何从包含各种值的复杂字符串的内容中提取单独的整数,例如:
NSString *testString = @"26 8 102 65 53 2 190 784 212";
我搜索了StackOverflow和其他地方,但没有找到针对此特定问题的答案。我想到了类似的东西:
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…
}
但是我不在这里,这个伪代码当然会失败。有人可以帮我解决一下第一眼的SEEMED问题吗?
答案 0 :(得分:1)
这是基于您之前的代码的代码段。
[ODBC DRIVERS]
Teradata Database ODBC Driver 16.20=Installed
[Teradata Database ODBC Driver 16.20]
Driver=/opt/teradata/client/16.20/odbc_64/lib/tdataodbc_sb64.so
APILevel=CORE
ConnectFunctions=YYY
DriverODBCVer=3.51
SQLLevel=1
输出
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);
}
答案 1 :(得分:1)
我喜欢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
收集整数作为练习留给读者。