這裏是文本文件:
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線輸入f中的文本你指定的。在文件的開頭有一個額外的換行符。這說明了一個額外的計數。我只能推測在實際文件中有一個額外的新行。也許到最後?
有一些事情我做了這項工作。 我改變@"/n"
到@"\n"
我們通過nil
到error:
不NULL
我記錄的NSMutableArray裏,我選擇了在可讀性第二步初始化的說明。 我也擺脫了文件頂部的額外換行符,並確保最後沒有一個換行符。
以防萬一,換行符爲\ n,而不是/ N ...但也許你已經寫/ N在您的文件... – Macmade 2010-07-23 16:46:58