使用 objective-c/cocoa touch 可以用来计算文件中换行符出现次数的最小代码是多少?
谢谢!
最佳答案
其他两个答案都是正确的,但需要注意的是它们需要将整个文件加载到内存中才能工作。
解决方法是使用 NSFileHandle
增量加载文件。像这样:
NSFileHandle * file = [NSFileHandle fileHandleForReadingAtPath:pathToFile];
NSUInteger chunkSize = 1024;
NSData * chunk = [file readDataOfLength:chunkSize];
NSUInteger numberOfNewlines = 0;
while ([chunk length] > 0) {
const unichar * bytes = (const unichar *)[chunk bytes];
for (int index = 0; index < [chunk length]; ++index) {
unichar character = (unichar)bytes[index];
if ([[NSCharacterSet newlineCharacterSet] characterIsMember:character]) {
numberOfNewlines++;
}
}
chunk = [file readDataOfLength:chunkSize];
}
关于objective-c - 计算文件中的换行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3791194/