我想要做這樣的事情:最佳方式,如果一個字符串在列表(沒有泛型)
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(常量AnsiString類型AText,串A-值的常量陣列):整數或和matchstr(常量AText:字符串; const的A-值:字符串的數組):布爾值;
喜歡的東西
Result := (AnsiIndexText('Hi',['Hello','Hi','Foo','Bar']) > -1);
或
Result := MatchStr('Hi', ['foo', 'Bar']);
AnsiIndexText返回0偏移 索引找到在 A-值匹配AText 不區分大小寫第一串。如果由AText指定的字符串 在 AValues中沒有 (可能不區分大小寫)匹配,則AnsiIndexText返回-1。 比較基於當前的 系統區域設置。
和matchstr確定是否有任何在該陣列的A-值串 匹配使用情況 大小寫的比較由AText指定的 字符串。它返回true 如果在 陣列匹配字符串中的至少一個,或虛假如果沒有 的字符串相匹配的。
注AnsiIndexText具有不區分大小寫,並和matchstr是大小寫敏感的,所以我想這取決於你的使用
編輯:2011年9月3日:剛剛發現這個答案,我想我會添加備註在Delphi 2010中,還有一個MatchText
函數,它與MatchStr
相同,但不區分大小寫。拉里 -
這裏是一個函數,它的工作:
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與絃樂每個字符串。只要你找到一個匹配,你可以退出for循環。
這個工作,請更新Delphi的一個代碼: 功能StringInArray(價值:字符串;字符串:字符串數組):布爾; var I:Integer; 開始 結果:=假; I:=低(字符串)爲高(字符串)做 結果:=結果或(值=字符串[I]); 結束; – 2008-10-29 12:57:41
很難做n00b,也不能編輯東西:( – 2008-10-29 12:58:20
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;
你可以試試這個:
Result := Pos(MyString, string1+string2+string3+string4) > 0
其實有一個更好的,在StrUtils.pas中搜索了一下,發現MatchStr返回一個布爾值: 結果:= MatchStr('Hi' ,['foo','Bar']); 請將它添加到您的答案 – 2008-10-29 13:48:41