What is the proper way to read a text file into an array of lines? I found the following on Rosetta Stone:
string[] readLines(string filename) {
auto f = File(filename);
scope(exit) f.close();
string[] lines;
foreach (str; f.byLine) {
lines ~= str.idup;
}
return lines;
}
but it looks like it's doing one array resize per line, which is pretty inefficient. I could keep track of the number of lines read in and resize the array via the standard doubling method
int i = 0;
foreach (str; f.byLine) {
if (lines.length <= i + 1) {
lines.length = lines.length * 2 + 1;
}
lines[i] = str.idup;
i++;
}
lines.length = i;
but that's enough boilerplate code that I have to wonder if I'm not just overlooking something in the standard library that already does this for me.
Edit: giving fwend's comment more visibility: this article describes in detail how the array allocator works, and why appending is handled efficiently by the runtime
All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.
Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.
Actually, D will double the array's reserved space whenever it runs out of room, so you don't need to do it by hand. There is a lot of information about D's arrays here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With