On Wednesday, 2 September 2015 at 15:04:10 UTC, cym13 wrote:
On Wednesday, 2 September 2015 at 13:46:54 UTC, Namal wrote:
Thx, cym. I have a question about a D strings though. In c++ I
would just reuse the string buffer with the "=" how can I
clear the string after i store a line in the buffer and do
something with it. I also tried to append a line to an array
of strings but it failed because the line is a char?
In D you can do as in C++:
buffer = ""; // or a brand new string
You can also reset a variable to its initial state (what you
would hav had if you hadn't initialized it) using:
buffer.init();
When reading files the default type you get is dchar[]. There
are different kind of strings in D, you way want to check
http://dlang.org/arrays.html#strings . If you want to append to
an array of strings, simply convert your line to type string:
import std.conv;
import std.stdio;
void main() {
string[] buffer;
foreach (line ; File("test.txt").byLine)
buffer ~= line.to!string; // <- Here is the magic
writeln(buffer);
}
Actually, even if converting works, what qznc did is better in
the case of file reading. And even better would be to use
.byLineCopy which basically does the same thing as qznc's
solution but more efficiently:
import std.stdio;
void main() {
string[] buffer;
foreach (line ; File("test.txt").byLineCopy)
buffer ~= line;
writeln(buffer);
}