简体   繁体   中英

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> . 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. 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

  1. U make your file exactly of Key=Value lines, not Key,Value
  2. U either need it case sensitive or do UpperCase over the file.

Then u use http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.TStrings.Values

To speed things up a bit you can use THashedStringList of IniFiles unit. There also was somethign similar in JCL in JclXML unit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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