如何从键值文件创建字符串的关联数组( string[strings] )?

How to create associative array of strings ( string[strings] ) from key-value file?

这里是我想要得到的关联数组的例子:

string [string] rlist = ["dima":"first", "masha":"second", "roma":"third"];

我阅读的文本文件结构非常简单:

peter = fourth ivan = fifth david = sixth

string [string] strarr;    
string txt = readText("test.txt");
foreach (t;txt.splitLines())
{
    // ??
}

有人可以建议方法吗?

尝试以下操作:

  import std.string : splitLines, strip;
  import std.file : readText;
  import std.algorithm : findSplit;

  string[string] strarr;
  string txt = readText("test.txt");

  foreach(t ; txt.splitLines()) {
    auto res = t.findSplit("=");
    string key = res[0].strip;
    string val = res[2].strip;
    strarr[key] = val;
  }

findSplit will return three ranges: the part before '=', '=', and the part after '='. strip 可用于删除 = 周围的空格,否则这些空格将包含在键和值中。

如果您想要更强大的解决方案,可以考虑使用 D 库来读取 config/ini 文件,例如 onyx-config, ctini, or dini.

可能是我,但我发现很难用 for 循环和临时变量进行推理,我宁愿做类似的事情:

import std.conv;
import std.stdio;
import std.array;
import std.algorithm;

void main() {
    string[string] dic = File("test")
                              .byLine
                              .map!(l => l.to!string.findSplit(" = "))
                              .map!(l => tuple( l[0], l[2] ))
                              .assocArray;
}

byLine:逐行阅读,比阅读整个内容然后拆分更好。

第一张图:按照 rcorre

的解释将每行分成三部分

第二张地图:根据分割线构建对

assocArray:从这些对构建关联数组。