xcode 逐行读取字符串(在 Objective-C 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5378961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read string line-by-line (in Objective-C)
提问by Timo
What is a fast and simple way to read a string line-by-line?
逐行读取字符串的快速而简单的方法是什么?
I am currently using Xcode, although solutions in any language are welcome.
我目前正在使用 Xcode,但欢迎使用任何语言的解决方案。
For reference, I would prefer to make a function that allows me to read it much like one could read lines from a file in C#:
作为参考,我更喜欢创建一个函数,让我可以像在 C# 中从文件中读取行一样读取它:
lineString = handle.ReadLine();
回答by DCurro
The answer does not explain how to read a LARGEtext file line by line. There is not nice solution in Objective-C for reading large text files without putting them into memory (which isn't always an option).
答案没有解释如何逐行读取LARGE文本文件。在 Objective-C 中没有很好的解决方案来读取大文本文件而不将它们放入内存(这并不总是一个选项)。
In these case I like to use the c methods:
在这些情况下,我喜欢使用 c 方法:
FILE* file = fopen("path to my file", "r");
size_t length;
char *cLine = fgetln(file,&length);
while (length>0) {
char str[length+1];
strncpy(str, cLine, length);
str[length] = '##代码##';
NSString *line = [NSString stringWithFormat:@"%s",str];
% Do what you want here.
cLine = fgetln(file,&length);
}
Note that fgetln will not keep your newline character. Also, We +1 the length of the str because we want to make space for the NULL termination.
请注意, fgetln 不会保留您的换行符。此外,我们将 str 的长度加 1,因为我们想为 NULL 终止腾出空间。
回答by Konrad77
These answers might help Objective-C: Reading a file line by line
这些答案可能有助于Objective-C:逐行读取文件