微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

| 我目前有一条记录(具有各种值)和三个具有特定分配值(例如名称等)的用户常数。 我可以将编辑框与一个用户进行比较,如下所示:
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;
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。