How to access duplicates in a TStringList (Views: 100)


I have a TStringList that looks something like:

a = one
b = two
c = three
c = four

Could someone please tell me to access both values of c? When I try to use (StringList.Values['c']) to get the value of c, I can only ever get the first value, and I need both. Even looping through every item in the list would be fine, but I can't get that to work either. StringList[I] in a for loop only gives me the whole line, like c=three, and I just want the value three.


Solve 1:

procedure GetMatchingValues(strKey: string; slSource, slResult: TStringList);
  i, nStart: integer;
  strKey := strKey + '=';
  nStart := Length(strKey) + 1;
  for i := 0 to slSource.Count - 1 do
    if Pos(strKey, slSource[i]) = 1 then
      slResult.Add(Copy(slSource[i], nStart, Length(slSource[i])));

Solve 2:

Try something like the following:

for i := 0 to SL.Count - 1 do
  temp := SL[i];
  p := pos('=', temp);
  key := copy(temp, 1, p - 1);
  if key = 'c' then
    value := copy(temp, p + 1, length(temp));

<< Back to main page