【问题标题】:Best way to find if a string is in a list (without generics)查找字符串是否在列表中的最佳方法(没有泛型)
【发布时间】:2008-10-29 12:37:47
【问题描述】:

我想做这样的事情:

Result = 'MyString' in [string1, string2, string3, string4];

这不能与字符串一起使用,我不想做这样的事情:

Result = (('MyString' = string1) or ('MyString' = string2));

另外我认为创建一个 StringList 来做这件事太复杂了。

还有其他方法可以实现吗?

谢谢。

【问题讨论】:

    标签: delphi delphi-2007


    【解决方案1】:

    您可以使用AnsiIndexText(const AnsiString AText, const array of string AValues):integerMatchStr(const AText: string; const AValues: array of string): Boolean;(均来自StrUtils 单位)

    类似:

    Result := (AnsiIndexText('Hi',['Hello','Hi','Foo','Bar']) > -1);
    

    Result := MatchStr('Hi', ['foo', 'Bar']); 
    

    AnsiIndexText 返回 0 偏移量 它找到的第一个字符串的索引 与 AText 匹配的 AValues 不区分大小写。如果字符串 AText 指定的没有 (可能不区分大小写)匹配 AValues,AnsiIndexText 返回 –1。 比较基于当前 系统语言环境。

    MatchStr 确定是否有任何 数组 AValues 中的字符串匹配 AText 使用 大小写指定的字符串 敏感比较。它返回真 如果至少有一个字符串在 数组匹配,如果都不匹配,则返回 false 字符串匹配。

    注意AnsiIndexText 不区分大小写,MatchStr 区分大小写,所以我想这取决于您的使用情况

    编辑:2011-09-3:刚刚找到这个答案,我想我会添加一个注释,在 Delphi 2010 中还有一个 MatchText 函数,它与 MatchStr 相同但不区分大小写。 -- 拉里

    【讨论】:

    • 其实还有一个更好的,只是在 StrUtils.pas 中搜索了一下,找到了返回布尔值的 MatchStr: Result := MatchStr('Hi', ['foo', 'Bar' ]);请将其添加到您的答案中。
    • MatchStr 和 MatchText 在 Delphi 2007 中也可用。
    • delphi 7 的任何等价物?
    • @JerryGagnon:在哪个单位?我在SysUtils 中找不到他们
    • @Fabrizio 他们在StrUtils
    【解决方案2】:

    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;
    

    【讨论】:

      【解决方案3】:

      这是一个完成这项工作的函数:

      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 中的每个字符串进行比较。一旦找到匹配项,就可以退出 for 循环。

      【讨论】:

      • 这行得通,请用 Delphi 更新你的代码: function StringInArray(Value: string; Strings: array of string): Boolean;变量 I:整数;开始结果:=假;对于 I := Low(Strings) to High(Strings) do Result := Result or (Value = Strings[I]);结束;
      猜你喜欢
      • 1970-01-01
      • 2010-09-07
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      相关资源
      最近更新 更多