答案 0 :(得分:4)
这是文本文件:
Feet sizes in England are measured in Barleycorns. Elephants laugh and cry. Trousers kill 12 people a year. The lion that roars in the MGM logo is called Volney. The wife of a Sultan is called a Sultana. Brad Pitt's real name is William. There are more than 5000 ladybird species. US lavatories are 100 times more dangerous than British ones. In 1996, 43,687 Americans were hospitalized after toilet disasters. The statue of liberty is made of bronze and was given to the Americans by the French. The Irish gave bagpipes to the Scots as a joke. It back fired! Your foot is the same length as the distance between your wrist and elbow. A rat can swim non-stop for 72 hours. The odds of being killed in a car crash in Britain are the same as being killed in an accident inside your own home: 1 in 10,000. In 1996, 12 people in Britain were rushed to hospital after a paperclip incident.
以下是代码:
NSString *title = @"facts";
NSString *type = @"txt";
NSString *separation = @"\n";
NSString *fileText = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:title ofType:type] encoding:NSMacOSRomanStringEncoding error:nil];
NSMutableArray *facts = [[NSMutableArray alloc]initWithArray:[fileText componentsSeparatedByString:separation]];
NSLog(@"%@", [facts description]);
这是输出数组:
(
"Feet sizes in England are measured in Barleycorns. ",
"Elephants laugh and cry. ",
"Trousers kill 12 people a year. ",
"The lion that roars in the MGM logo is called Volney. ",
"The wife of a Sultan is called a Sultana. ",
"Brad Pitt's real name is William. ",
"There are more than 5000 ladybird species. ",
"US lavatories are 100 times more dangerous than British ones. In 1996, 43,687 Americans were hospitalized after toilet disasters. ",
"The statue of liberty is made of bronze and was given to the Americans by the French. ",
"The Irish gave bagpipes to the Scots as a joke. It back fired! ",
"Your foot is the same length as the distance between your wrist and elbow. ",
"A rat can swim non-stop for 72 hours. ",
"The odds of being killed in a car crash in Britain are the same as being killed in an accident inside your own home: 1 in 10,000. ",
"In 1996, 12 people in Britain were rushed to hospital after a paperclip incident. "
)
您指定的输入文件中有14行文本。文件开头有一个额外的换行符。这是额外计数之一。我只能猜测实际文件中有一个额外的新行。或许到最后?
我做了一些事情来完成这项工作。
我将@"/n"
更改为@"\n"
我们将nil
传递给error:
而不是NULL
我记录了NSMutableArray的描述,为了便于阅读,我选择在第二步中进行初始化。
我还删除了文件顶部的额外换行符,并确保最后没有换行符。
答案 1 :(得分:1)