我想要做类似于这样的事情:
Result = 'MyString' in [string1, string2, string3, string4];
这不能与字符串一起使用,我不想做像这样的事情:
Result = (('MyString' = string1) or ('MyString' = string2));
我认为创建一个StringList来做这件事情太复杂了。
有没有其他方法可以实现这个功能呢?
谢谢。
我想要做类似于这样的事情:
Result = 'MyString' in [string1, string2, string3, string4];
这不能与字符串一起使用,我不想做像这样的事情:
Result = (('MyString' = string1) or ('MyString' = string2));
我认为创建一个StringList来做这件事情太复杂了。
有没有其他方法可以实现这个功能呢?
谢谢。
你可以使用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函数相同,但是不区分大小写。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;
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;
SysUtils
中找不到它们。 - FabrizioStrUtils
中。 - Re0sless