不使用泛型,查找字符串是否在列表中的最佳方法

31

我想要做类似于这样的事情:

Result = 'MyString' in [string1, string2, string3, string4];

这不能与字符串一起使用,我不想做像这样的事情:

Result = (('MyString' = string1) or ('MyString' = string2));

我认为创建一个StringList来做这件事情太复杂了。

有没有其他方法可以实现这个功能呢?

谢谢。

3个回答

70

你可以使用AnsiIndexText(const AnsiString AText,const array of string AValues):integer或者MatchStr(const AText:string; const AValues:array of string):Boolean;(两者均来自于StrUtils单元)

类似于:

Result := (AnsiIndexText('Hi',['Hello','Hi','Foo','Bar']) > -1);
或者
Result := MatchStr('Hi', ['foo', 'Bar']); 
AnsiIndexText函数会在AValues数组中查找第一个不区分大小写匹配AText字符串的下标。如果AText字符串在AValues数组中没有(不区分大小写)匹配项,那么AnsiIndexText函数返回-1。比较是基于当前系统的语言环境进行的。 MatchStr函数用于判断数组AValues中的任何一个字符串是否与指定的字符串AText(使用区分大小写的比较)匹配。如果数组中至少有一个字符串与指定字符串匹配,则函数返回true;否则,返回false。 注意,AnsiIndexText函数不区分大小写,而MatchStr函数区分大小写,所以具体使用取决于上下文。另外,在Delphi 2010中还有一个MatchText函数,它与MatchStr函数相同,但是不区分大小写。

实际上有一个更好的方法,只需要在 StrUtils.pas 中查找一下,就能找到 MatchStr 函数,它返回一个布尔值: Result := MatchStr('Hi', ['foo', 'Bar']); 请将其添加到您的答案中。 - Fabio Gomes
MatchStr和MatchText在Delphi 2007中也是可用的。 - Jerry Gagnon
Delphi 7 有任何等效替代品吗? - CyprUS
1
@JerryGagnon:在哪个单元里?我在SysUtils中找不到它们。 - Fabrizio
1
@Fabrizio,它们在StrUtils中。 - Re0sless

9

Burkhard的代码可以工作,但即使找到匹配项,它也会不必要地遍历整个列表。

更好的方法:

function StringInArray(const Value: string; Strings: array of string): Boolean;
var I: Integer;
begin
  Result := True;
  for I := Low(Strings) to High(Strings) do
    if Strings[i] = Value then Exit;
  Result := False;
end;

2
这里有一个完成任务的函数:

function StringInArray(Value: string; Strings: array of string): Boolean;
var I: Integer;
begin
  Result := False;
  for I := Low(Strings) to High(Strings) do
  Result := Result or (Value = Strings[I]);
end;

实际上,您会将 MyString 与 Strings 中的每个字符串进行比较。一旦找到一个匹配项,就可以退出 for 循环。

这个函数是有效的,请使用Delphi代码更新你的代码: function StringInArray(Value: string; Strings: array of string): Boolean; var I: Integer; begin Result := False; for I := Low(Strings) to High(Strings) do Result := Result or (Value = Strings[I]); end; - Fabio Gomes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接