31

我想做这样的事情:

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

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

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

另外我认为创建一个 StringList 来做到这一点太复杂了。

还有其他方法可以实现这一目标吗?

谢谢。

4

3 回答 3

68

您可以使用AnsiIndexText(const AnsiString AText, const array of string AValues):integerMatchStr(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 不区分大小写的第一个字符串的 0 偏移索引。如果 AText 指定的字符串在 AValues 中没有(可能不区分大小写)匹配,则 AnsiIndexText 返回 –1。比较基于当前系统区域设置。

MatchStr 使用区分大小写的比较确定数组 AValues 中的任何字符串是否与 AText 指定的字符串匹配。如果数组中至少有一个字符串匹配,则返回 true,如果没有字符串匹配,则返回 false。

注意AnsiIndexText不区分大小写并且MatchStr区分大小写,所以我想这取决于您的使用

编辑:2011-09-3:刚刚找到这个答案,并认为我会添加一个注释,在 Delphi 2010 中还有一个与大小写MatchText相同MatchStr但不区分大小写的函数。——拉里

于 2008-10-29T13:15:48.237 回答
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;
于 2008-10-29T13:10:35.127 回答
1

这是一个完成这项工作的函数:

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 循环。

于 2008-10-29T12:49:22.033 回答