How do I concisely check whether a string equals any of several values?
I currently have one record (with various values) and three user constants with specific assigned values (e.g. names, etc.).
I can compare an edit box against one user like this:
if edit1.text = user1
then xxxx
This is all well, but how do I specify that the edit box must check between the three different users?
Example:
if edit1.t开发者_JS百科ext = user1 to user3
then xxxx
How Do I go about doing this?
Recent versions of Delphi (I use XE) have unit StrUtils.pas which contains
function MatchText(const AText: string; const AValues: array of string): Boolean;
function MatchStr(const AText: string; const AValues: array of string): Boolean;
MatchStr is the case sensitive version.
Your problem can now be solved like this:
if MatchStr(edit1.text, [user1, user2, user3])
then xxxx
You can use AnsiMatchStr()/AnsiMatchText() to check if a string matches one of the string in an array. AnsiIndexStr()/AnsiIndexText() also return the index of the matched string, and thereby can be useful in case of statements.
For a set which might grow later at runtime, I might declare a TStringList, if I have a class instance to hold the "acceptable values" and replace the large if (x=a1) or (x=a2) or (x=a3)....
sequence with:
// FAcceptableValues is TStringList I set up elsewhere, such as my class constructor.
if FAcceptableValues.IndexOf(x)>=0 then ...
That has the benefit of being customizeable. In the case of your logic, I would consider making a list of controls, and doing a Match function:
var
Users:TList<TUser>;
Edits:TList<TEdit>;
begin
... other stuff like setup of FUsers/FEdits.
if Match(Users,Edits) then ...
Match could be written as a simple for next loop:
For U in Users do
for E in Edits do
if U.Text=E.Text then
begin
result := true;
exit
end;
Delphi doesn't support the use of strings in case
statements so you have to do it the hard way.
if ((user1.name = edit1.text) and (user1.surname = edit2.text)) or
((user2.name = edit1.text) and (user2.surname = edit2.text)) or
((user3.name = edit1.text) and (user3.surname = edit2.text))
then xxxx
精彩评论