简体   繁体   English

如何从逗号分隔的字符串对列表中填充TDictionay?

[英]How do i fill a TDictionay from a list of comma-separated string pairs?

I want to have a text file with a list of strings (say for example comma separated with key and values that I can use for auto replacement) and store each key-value pair in a TDictionary<string, string> . 我想要一个带有字符串列表的文本文件(例如,用逗号分隔的逗号和可用于自动替换的值),并将每个键值对存储在TDictionary<string, string> How do I populate the dictionary? 如何填充字典?

From your comment it seems you want to know how to pull out some key value pairs, comma separated, into a dictionary. 从您的评论看来,您似乎想知道如何将一些逗号分隔的键值对提取到字典中。 Here's a basic example: 这是一个基本示例:

procedure PopulateKeyValueDict(Strings: TStrings;
  Dict: TDictionary<string, string>);
var
  CommaPos: Integer;
  Line: string;
  Key, Value: string;
begin
  for Line in Strings do
  begin
    CommaPos := Pos(',', Line);
    if CommaPos=0 then
      raise Exception.CreateFmt(
        'Could find comma separated key/value pair in ''%s''',
        [Line]
      );
    Key := Copy(Line, 1, CommaPos-1);
    Value := Copy(Line, CommaPos+1, MaxInt);
    Dict.Add(Key, Value);
  end;
end;

You may likely want to add more error-checking and so on, but I'm assuming you already know how to do that. 您可能想要添加更多错误检查等,但是我假设您已经知道该怎么做。 This example illustrates splitting a line on the first comma, and also how to populate a dictionary. 本示例说明了在第一个逗号上分割一行,以及如何填充字典。

In order to use it you need to transfer your file to a TStrings object. 为了使用它,您需要将文件传输到TStrings对象。 That's routine: 这是例行程序:

var
  Strings: TStringList;
....
Strings := TStringList.Create;
try
  Strings.LoadFromFile(FileName);
  PopulateKeyValueDict(Strings, Dict);
finally
  Strings.Free;
end;

If you only have one-to-one key-value relation (not like three key words "apple" and "apples" and "McIntoshes" would be turned into "McIntosh") - then probably the simpliest way would be to use TStringList, providing that 如果您只有一对一的键/值关系(不像三个关键字“ apple”,“ apples”和“ McIntoshes”会变成“ McIntosh”),那么最简单的方法可能是使用TStringList,提供了

  1. U make your file exactly of Key=Value lines, not Key,Value U使您的文件恰好是Key=Value行,而不是Key,Value
  2. U either need it case sensitive or do UpperCase over the file. 您要么需要区分大小写,要么需要对文件进行UpperCase处理。

Then u use http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.TStrings.Values 然后,您使用http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.TStrings.Values

To speed things up a bit you can use THashedStringList of IniFiles unit. 为了加快速度,您可以使用IniFiles单元的THashedStringList。 There also was somethign similar in JCL in JclXML unit. JclXML单元中的JCL中也有类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM