Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: TStringList.Contains?

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?

like image 576
chollinger Avatar asked Oct 09 '12 09:10

chollinger


2 Answers

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.

like image 121
Toon Krijthe Avatar answered Nov 13 '22 14:11

Toon Krijthe


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

like image 37
Remy Lebeau Avatar answered Nov 13 '22 13:11

Remy Lebeau