我正在学习D并尝试拆分字符串:
import std.stdio;
import std.string;
auto file = File(path, "r");
foreach (line; file.byLine) {
string[] parts = split(line);
Run Code Online (Sandbox Code Playgroud)
这无法编译:
Error: cannot implicitly convert expression (split(line)) of type char[][] to string[]
Run Code Online (Sandbox Code Playgroud)
这有效:
auto file = File(path, "r");
foreach (line; file.byLine) {
char[][] parts = split(line);
Run Code Online (Sandbox Code Playgroud)
但为什么我要使用char[][]?据我了解文档,它说split返回a string[],我更喜欢.
使用split(line.idup);
split是一个模板函数,返回类型取决于它的参数.file.byLine.front返回a char[]也因性能原因而重复使用.因此,如果在当前循环迭代之后需要部件,则必须执行dup或者idup,无论您需要什么.