2006. május 15., hétfő

How to access duplicates in a TStringList


Problem/Question/Abstract:

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.

Answer:

Solve 1:

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


Solve 2:

Try something like the following:

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

Nincsenek megjegyzések:

Megjegyzés küldése