简体   繁体   English

可以使用IndexOf在Delphi的TStringList中搜索两个或多个备用字符串吗?

[英]Can IndexOf be used to search for two or more alternate strings in a TStringList in Delphi?

I have used IndexOf() in order to extract the index of a TStrinList in Delphi 2005. At the moment it only searches for one string but I would like it to search for alternative strings. 我已经使用IndexOf()来提取Delphi 2005中TStrinList的索引。目前它只搜索一个字符串,但我希望它搜索替代字符串。 For example, to search for 'String A', 'String B' or 'String C' and give me the index of whichever is found first. 例如,要搜索“字符串A”,“字符串B”或“字符串C”,并为我提供先找到的索引。

Is it possible to do this with IndexOf() or is there another method? 是否可以使用IndexOf()执行此操作或是否有其他方法?

There is no built in functionality that does this. 没有内置功能可以做到这一点。

You can use multiple calls to IndexOf . 您可以使用多个IndexOf调用。 Then take the smallest index that is not equal to -1 . 然后取最小的索引不等于-1 This is quick and easy to implement but will not have optimal performance. 这很容易实现,但不具备最佳性能。

Another option, if performance is critical, would be to roll your own function to perform the search. 如果性能至关重要,另一个选择是滚动您自己的功能来执行搜索。 Simple enough linear search for unordered lists. 对无序列表进行简单的线性搜索。 A bit more complex if you want to use binary search on an ordered list. 如果要在有序列表上使用二进制搜索,则会更复杂一些。

There's no built-in method to do this, and no way to use a single call to IndexOf to achieve it either. 没有内置方法可以做到这一点,也没有办法使用单个调用IndexOf来实现它。

If you need to find the one that occurs first, you'll need to make three separate calls to IndexOf , one for each of the values, and return the one with the lowest index. 如果您需要找到首先出现的那个,您需要对IndexOf进行三次单独调用,每个值对应一个值,并返回索引最低的一个。 An easy wrapper to do so would be something like this (along with a console application to test it): 一个简单的包装器就是这样的(以及一个用于测试它的控制台应用程序):

program Project2;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, Classes;


function GetLowestIndexOf(const SL: TStrings; const AValues: array of string): Integer;
var
  Idx, Temp: Integer;
begin
  // Initialize with first test results (which may be -1)
  Result := SL.IndexOf(AValues[0]);
  for Idx := 1 to High(AValues) do
  begin
    Temp := SL.IndexOf(AValues[Idx]);
    if (Temp > -1) and ((Temp < Result) or (Result = -1)) then
      Result := Temp;
  end;
end;

var
  Test: Integer;
  SL: TStringList;

begin
  SL := TStringList.Create;
  SL.Text := 'Some Value'#13'String C'#13'Another Value'#13'Something Else'#13 +
             'String A'#13'Yet Another'#13'String B';
  Test := GetLowestIndexOf(SL, ['String A', 'String B', 'String C']);
  WriteLn(SL[Test]);
  ReadLn;
end.

If your list of items to check for is long, it might be worthwhile to add in an additional test to break out of the loop if you've already found the lowest possible index (between 1 and the length of the shortest value), as there can't be one. 如果要检查的项目列表很长,那么如果您已经找到可能的最低索引(在1和最短值的长度之间),则可能值得添加一个额外的测试来突破循环,如不可能有一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM