Delphi: TStringList.Contains?

15,834

Solution 1

Not integrated, but you can use the Pos function on the Text property:

Pos('This is a', List.Text)

And if you want it to be integrated, you can create a class helper for TStrings.

Solution 2

Not directly, no. You would have to either:

1) call Pos() on the Text property, which is not efficient if you have a lot of strings.

2) loop through the list manually, calling Pos() on each String. More efficient, but also more coding.

3) derive a new class from TStringList and override its virtual CompareStrings() method to compare strings however you want (the default implementation simple calls AnsiCompareStr() or AnsiCompareText(), depending on the CaseSensitive property). Return 0 if you find a match. You can then use the TStringList.Find() method, which calls CompareStrings() internally (be careful, so does TStringList.Sort(), but you can avoid that if you call TStringList.CustomSort() instead).

Share:
15,834
chollinger
Author by

chollinger

Updated on June 09, 2022

Comments

  • chollinger
    chollinger almost 2 years

    Is there any integrated solution in Delphi 2007 to check whether a TStringList contains a part of a certain value?

    e.g.:

    List.AddObject('This is a string', customStringObject1); 
    List.AddObject('This is a mushroom', customStringObject2); 
    List.AddObject('Random stuff', customStringObject3); 
    

    Searching for "This is a" is supposed to deliver me "true", since the first two elements contain this partwise.

    The only method i'm aware of so far is TStringList.find(string,integer), but this performs a complete string comparision, i.e. only searching for This is a string will return true.

    Any suggestions?