首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Objective中的百分比符号(%)解析文件

使用Objective中的百分比符号(%)解析文件
EN

Stack Overflow用户
提问于 2016-07-22 00:14:09
回答 2查看 77关注 0票数 0

我正在为财富文件写一个解析器。“财富”( Fortune )是一个在*nix平台上的小型应用程序,它只是随机打印一个“财富”。“财富”文件是直截了当的文本,每个“财富”都在自己的行上用百分比签名分隔。例如:

代码语言:javascript
复制
A little suffering is good for the soul.
                -- Kirk, "The Corbomite Maneuver", stardate 1514.0
%
A man either lives life as it happens to him, meets it head-on and
licks it, or he turns his back on it and starts to wither away.
                -- Dr. Boyce, "The Menagerie" ("The Cage"), star date unknown
%

我所发现的是,在解析文件时,stringWithContentsOfFile返回一个带有%标志的字符串。例如:

代码语言:javascript
复制
@"A little suffering is good for the soul.\n\t\t-- Kirk, \"The Corbomite Maneuver\", stardate 1514.0\n%\nA man either lives life as it happens to him, meets it head-on and\nlicks it, or he turns his back on it and starts to wither away.\n\t\t-- Dr. Boyce, \"The Menagerie\" (\"The Cage\"), stardate unknown\n%"

但是,当我对文件内容调用componentsSeparatedByCharactersInSet时,所有内容都被解析为字符串,除了百分比符号,即NSTaggedPointerString。当我把线条打印出来的时候,百分之百的符号就消失了。

这是因为百分比符号是字符串的格式说明符吗?我认为,在这种情况下,最初的内容拉会逃脱那些。

下面是代码:

代码语言:javascript
复制
NSFileManager *fileManager;
fileManager = [NSFileManager defaultManager];
NSStringEncoding stringEncoding;
//    NSString *fileContents = [NSString stringWithContentsOfFile:fileName encoding:NSASCIIStringEncoding error:nil];
NSString *fileContents = [NSString stringWithContentsOfFile:fileName usedEncoding:&stringEncoding error:nil];
NSArray *fileLines = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

所使用的编码最终是UTF-8。您可以看到,我也尝试过指定普通的ASCII,但结果是相同的。

所以问题是,我如何保留百分比的符号?或者,我可以使用它作为分隔符,然后分别解析每个后续结果。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-22 01:12:25

您正在调用NSLog(),但将行字符串作为格式字符串传递。类似于:

代码语言:javascript
复制
NSLog(lineString);

因此,行字符串中的任何百分比字符都被解释为格式说明符。您不应该(几乎)将来自外部来源的字符串(即在代码- as格式字符串中没有硬编码的字符串)传递给任何函数(NSLog()printf()+[NSString stringWithFormat:]等)。这是不安全的,你有时会得到意想不到的结果,就像你看到的。

您应该始终记录这样的单个字符串:

代码语言:javascript
复制
NSLog(@"%@", lineString);

也就是说,您需要传递一个硬编码的格式字符串,并使用外部字符串作为数据进行格式化。

票数 1
EN

Stack Overflow用户

发布于 2016-07-22 01:10:04

NSTaggedPointerString只是NSString的子类。您可以在任何地方使用NSString。

但在你的琴弦里

代码语言:javascript
复制
@"A little suffering is good for the soul.\n\t\t-- Kirk, \"The Corbomite Maneuver\", stardate 1514.0\n%\nA man either lives life as it happens to him, meets it head-on and\nlicks it, or he turns his back on it and starts to wither away.\n\t\t-- Dr. Boyce, \"The Menagerie\" (\"The Cage\"), stardate unknown\n%"

符号%不是百分比符号。在目标中,C%符号被声明为%标记的两倍。

代码语言:javascript
复制
@"%%"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38516285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档