Objective-C 中的 Sscanf 等价物 [英] Sscanf Equivalent in Objective-C
问题描述
我目前正在用 Objective-C 编写波前 OBJ 加载器,我正在尝试找出如何以类似于 C 中的 sscanf() 函数的方式解析来自 NSString 的数据.
I'm currently writing a wavefront OBJ loader in Objective-C and I'm trying to figure out how to parse data from an NSString in a similar manner to the sscanf() function in C.
OBJ 文件在顶点、纹理坐标和法线的 x、y、z 三元组中定义面,例如:
OBJ files define faces in x,y,z triplets of vertices, texture coordinates, and normals such as:
f 1.43//2.43 1.11//2.33 3.14//0.009
我目前不关心纹理坐标.在 C 中,解析这一行的一种简单方法是这样的语句:
I'm not concerned about texture coordinates at the current moment. In C, an easy way to parse this line would be a statement such as:
sscanf(buf, "f %d//%d %d//%d %d//%d", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]);
显然,如果不先将 NSStrings 转换为 C 样式字符串,就不能在 sscanf() 中使用它们,但我想知道是否有更优雅的方法来执行此操作而不进行此类转换.
Obviously, NSStrings can't be used in a sscanf() without first converting them to a C-style string, but I'm wondering if there's a more elegant way to performing this without doing such a conversion.
推荐答案
NSScanner 类可以解析字符串中的数字,尽管它不能用作 sscanf 的替代品.
The NSScanner class can parse numbers in strings, although it can't be used as a drop-in replacement for sscanf.
编辑:这是一种使用方法.也可以将/
放入要跳过的字符列表中.
Edit: here's one way to use it. You can also put the /
into the list of characters to be skipped.
float temp[6];
NSString *objContent = @"f 1.43//2.43 1.11//2.33 3.14//0.009";
NSScanner *objScanner = [NSScanner scannerWithString:objContent];
// Skip the first character.
[objScanner scanString:@"f " intoString:nil];
// Read the numbers.
NSInteger index=0;
BOOL parsed=YES;
while ((index<6)&&(parsed))
{
parsed=[objScanner scanFloat:&temp[index]];
// Skip the slashes.
[objScanner scanString:@"//" intoString:nil];
NSLog(@"Parsed %f", temp[index]);
index++;
}
这篇关于Objective-C 中的 Sscanf 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!