我有一个 txt 文件,它被复制到我的 Xcode 项目的支持文件中。txt 文件中的数据格式为:
abacus@frame with balls for calculating
abate@to lessen to subside
abdication@giving up control authority
aberration@straying away from what is normal
....................around 4000 lines
我已经使用以下代码成功地从文件中提取了数据:
NSString *greFileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"grewords" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
self.greWordsArray = [NSMutableArray arrayWithArray:[greFileString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
当我打印 greWordsArray 时,我可以在日志中看到以下输出
"abacus@frame",
with,
balls,
for,
calculating,
"",
"abate@to",
lessen,
to,
subside,
"",
"abdication@giving",
up,
control,
authority,
"",
"aberration@straying",
away,
from,
what,
is,
normal,
"",
但我想要两个独立数组中的值,一个持有算盘,减弱,退位,权威偏差和其他带有框架的数组,用于计算,减少消退,放弃控制,偏离正常,即一个数组持有字符串@ 符号之前和 @ 符号之后
我知道有几种方法,例如检查特殊字符方法,通过替换字符串的出现来字符串,使用字符集,但事实是因为我的字符串 greFileString 是一个包含多个字符串的包,如果我尝试这些方法中的任何一种,只有 abacus 得到添加到数组中,但我希望将算盘,减弱,退位,像差添加到数组中。
编辑
根据 H2CO3 的建议,我实施了以下方式:
NSString *greFileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"grewords" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
NSArray *greData = [NSArray arrayWithArray:[greFileString componentsSeparatedByString:@"@"]];
self.greWordsArray = [NSMutableArray array];
self.greWordHints = [NSMutableArray array];
for (NSString *greWord in greData)
{
if ([greWord characterAtIndex:0] == (unichar)'@')
{
[greWordHints addObject:greWord];
}
else
{
[greWordsArray addObject:greWord];
}
}
NSLog(@"gre words are %@",greWordsArray);
NSLog(@"gre hints are %@",greWordHints);
这是记录的输出:
gre words are (
abacus,
"frame with balls for calculating
\nabate",
"to lessen to subside
\nabdication",
"giving up control authority
\naberration",
"straying away from what is normal
\nabet",
"help/encourage somebody (in doing wrong)
\nabeyance",
"suspended action
\nabhor",
"to hate to detest
gre hints are (
)
有人可以指导我吗?