如何简洁地检查字符串是否等于多个值中的任何一个?

问题描述

| 我目前有一条记录(具有各种值)和三个具有特定分配值(例如名称等)的用户常数。 我可以将编辑框与一个用户进行比较,如下所示:
if edit1.text = user1 
 then xxxx
一切都很好,但是如何指定编辑框必须在三个不同的用户之间进行检查? 例:
if edit1.text = user1 to user3
 then xxxx
我该怎么做?     

解决方法

        Delphi不支持在
case
语句中使用字符串,因此您必须采用困难的方式。
 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
    ,        Delphi(我使用XE)的最新版本具有StrUtils.pas单元,其中包含
function MatchText(const AText: string; const AValues: array of string): Boolean;
function MatchStr(const AText: string; const AValues: array of string): Boolean;
MatchStr是区分大小写的版本。 您的问题现在可以像这样解决:
if MatchStr(edit1.text,[user1,user2,user3])
  then xxxx
    ,        您可以使用AnsiMatchStr()/ AnsiMatchText()检查字符串是否与数组中的字符串之一匹配。 AnsiIndexStr()/ AnsiIndexText()也返回匹配的字符串的索引,因此对于语句来说很有用。     ,        对于可能在运行时稍后增长的集合,如果我有一个类实例来保存\“ acceptable values \”并将其替换为大的
if (x=a1) or (x=a2) or (x=a3)....
序列,则可以声明一个TStringList。
 // FAcceptableValues is TStringList I set up elsewhere,such as my class constructor.
 if FAcceptableValues.IndexOf(x)>=0 then ...
这具有可定制的好处。就您的逻辑而言,我将考虑制作一个控件列表并执行Match函数:
 var 
   Users:TList<TUser>;
   Edits:TList<TEdit>;
 begin
    ... other stuff like setup of FUsers/FEdits.
    if Match(Users,Edits) then ... 
Match可以写为下一个循环的简单代码:
 For U in Users do 
     for E in Edits do
          if U.Text=E.Text then 
            begin 
             result := true;
             exit
            end;
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...