How to save and load a list of key-value pairs in a string?

I have a list of strings and the values ​​that they should replace. I try to combine them into a list, for example, 'O'='0',' .'='.', ... , so it’s easy for me to edit it and add more pairs of replacements.

Currently, the best way I can think of:

 var ListaLimpeza : TStringList; begin ListaLimpeza := TStringList.Create; ListaLimpeza.Delimiter := '|'; ListaLimpeza.QuoteChar := '"'; ListaLimpeza.DelimitedText := 'O=0 | " .=."'; ShowMessage('1o Valor = '+ListaLimpeza.Names[1]+' e 2o Valor = '+ListaLimpeza.ValueFromIndex[1]); 

This works, but it is not very good for visual images, since I cannot encode the previous line (for ex ' .' ), As it (which is very visual for the SPACE character), only as ( " . ), So that = works to assign a name and value to a TStringList.

+4
source share
1 answer

By default, Names and Values should be separated = in the style of Windows INI files. There is no way AFAICT change this delimiter. As @SirRufo points out in a comment (and which I never noticed), you can change this using the TStringList.NameValueSeparator property.

This will give you an idea of ​​what Delphi thinks in your TStringList , which is not how you think:

 procedure TForm1.FormCreate(Sender: TObject); var SL: TStringList; Temp: string; i: Integer; begin SL := TStringList.Create; SL.Delimiter := '|'; SL.QuoteChar := '"'; SL.StrictDelimiter := True; SL.DelimitedText := 'O=0 | ! .!=!.!'; Temp := 'Count: ' + IntToStr(SL.Count) + #13; for i := 0 to SL.Count - 1 do Temp := Temp + Format('Name: %s Value: %s'#13, [SL.Names[i], SL.ValueFromIndex[i]]); ShowMessage(Temp); end; 

This produces this conclusion:

Sample ShowMessage output from above code

TStringList Names / values ​​probably won't do what you need. It's not clear what your actual goal is, but it seems that a simple text file with a simple list of text|replacement and a simple parsing of this file will work, and you can easily use a TStringList to read / write from this file, but I don't see any way to do parsing is easy, except to do it yourself. You can use an array to store pairs when parsing them:

 type TReplacePair = record TextValue: string; ReplaceValue: string; end; TReplacePairs = array of TReplacePair; function GetReplacementPairs: TReplacePairs; var ConfigInfo: TStringList; i, Split: Integer; begin ConfigInfo := TStringList.Create; try ConfigInfo.LoadFromFile('ReplacementPairs.txt'); SetLength(Result, ConfigInfo.Count); for i := 0 to ConfigInfo.Count - 1 do begin Split := Pos('|`, ConfigInfo[i]; Result[i].TextValue := Copy(ConfigInfo[i], 1, Split - 1); Result[i].ReplaceValue := Copy(ConfigInfo[i], Split + 1, MaxInt); end; finally ConfigInfo.Free; end; end; 

Then you can fill in all the controls needed to edit / add / remove substitution pairs, and simply cancel the read operation to write them back for saving.

+5
source

Source: https://habr.com/ru/post/1484320/


All Articles