对于TStringList.Find函数,我有话要说

在Delphi中,TStringList中有一个叫Find的Function。它的作用是在一个StringList中查找一个string,并且返回这个string在StringList中的索引。Delphi Help中的说明如下:

Locates the index for a string in a sorted list and indicates whether a string with that value already exists in the list.

Delphi syntax:

function Find(const S: string; var Index: Integer): Boolean; virtual;

C++ syntax:

virtual bool __fastcall Find(const AnsiString S, int &Index);

Description

Use Find to obtain the index in a sorted list where the string S should be added. If the string S, or a string that differs from S only in case when CaseSensitive is false, already exists in the list, Find returns true. If the list does not contain a string that matches S, Find returns false. The index where S should go is returned in the Index parameter. The value of Index is zero-based, where the first string has the index 0, the second string has the index 1, and so on.

Note:    Only use Find with sorted lists. For unsorted lists, use the IndexOf method instead.

如上所述,这个Function如果想要执行正确的话,是有前提的,那就是StringList必须是先进行过排序的。

既然如此,为什么不把排序做在Function内部呢,这样的话就不至于由于不知道这个前提条件,而使这个Function使用错误。

或者把Function的名字再改的更直观易懂一点,比如:FindSort等类似的。

当然,如果简单的把StringList进行排序,再查找,会破坏掉了原数据的完整性。所以,如果把排序放在Function内部的话,可以把StringList复制一份再进行操作。

如下是我的伪代码:

strlstTmp: TStringList;

self.CopyTo(strlstTmp);

strlstTmp.Sort();

strlstTmp.Find(strToFind); // strToFind: 需要被查找的string

Index := self.IndexOf(strToFind); // Index: string所在StringList的索引位置。

原文地址:https://www.cnblogs.com/larson/p/2674473.html