私はこのようなことをしたい:
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 は、大文字と小文字を区別せずに AText と一致する AValues で最初に見つかった文字列の 0 オフセット インデックスを返します 。AText で指定された文字列が AValues に (おそらく大文字と小文字を区別しない) 一致しない場合、AnsiIndexText は –1 を返します。比較は、現在のシステム ロケールに基づいています。
MatchStr は、大文字と小文字を区別する比較を使用して、配列 AValues 内のいずれかの文字列が AText で指定された文字列と一致するかどうかを判断します。配列内の文字列の少なくとも 1 つが一致する場合は true を返し、どの文字列も一致しない場合は false を返します。
注AnsiIndexText
は大文字と小文字を区別せず、大文字と小文字をMatchStr
区別するので、用途に依存すると思います
編集: 2011-09-3 : この回答を見つけたので、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;
実際、MyString を Strings の各文字列と比較します。一致するものが 1 つ見つかるとすぐに、for ループを終了できます。