string 如何检查数组中是否存在字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6320003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:08:25  来源:igfitidea点击:

How do I check whether a string exists in an array?

arraysstringdelphi

提问by maxfax

I have this code:

我有这个代码:

var
  ExtString: string;
const
  Extensions : array[0..4] of string = ('.rar', '.zip', '.doc', '.jpg', '.gif');

if ExtString in Extensions then

On the last line, I get an error:

在最后一行,我收到一个错误:

[DCC Error] E2015 Operator ('then') not applicable to this operand type

[DCC 错误] E2015 运算符 ('then') 不适用于此操作数类型

I think I can not do this, so how can I properly perform my task?

我想我不能这样做,那么我该如何正确执行我的任务?

回答by Robert Love

As you have found you can't check for a String in an Array of String, using in.

正如您发现的那样,您无法使用in.

You could use this function instead of the ifstatement.

您可以使用此函数而不是if语句。

function StrInArray(const Value : String;const ArrayOfString : Array of String) : Boolean;
var
 Loop : String;
begin
  for Loop in ArrayOfString do
  begin
    if Value = Loop then
    begin
       Exit(true);
    end;
  end;
  result := false;
end;

You can call it like this.

你可以这样称呼它。

if StrInArray(ExtString,Extensions) then

if StrInArray(ExtString,Extensions) then

The StrUtils.pashas this already defined.

StrUtils.pas这个已经定义了。

function MatchStr(const AText: string; const AValues: array of string): Boolean; 

回答by Misha

Initialise a TStringList instance from the constant array and use IndexOf().

从常量数组​​初始化一个 TStringList 实例并使用 IndexOf()。

回答by Germán Estévez -Neftalí-

You can use the funcions IndexStr(case sensitive) or IndexText(case insensitive) from System.StrUtilsto find the string inside the array and retrive the index.

您可以使用函数IndexStr(区分大小写)或IndexText(不区分大小写) fromSystem.StrUtils来查找数组内的字符串并检索索引。

var
  ExtString: string;
const
  Extensions : array[0..4] of string = ('.rar', '.zip', '.doc', '.jpg', '.gif');
begin
  if (IndexStr(ExtString, Extensions) <> -1) then
    ShowMessage('Finded')
  else
    ShowMessage('Not finded');

Link to help in docwiki from embarcadero.

来自 embarcadero 的 docwiki 帮助链接

回答by Joseph Ptheitroadier

Sometimes the simplest solutions aren't the most obvious

有时最简单的解决方案并不是最明显的

var
  ExtString: string;
const
  Extensions = ('.rar,.zip,.doc,.jpg,.gif');

if Pos(ExtString, Extensions) > 0 then

or with .Netrification in the new StrUtils library, which I love!!! Think Helpers!

或者使用我喜欢的新 StrUtils 库中的 .Netrification !!!想想帮手!

if Extensions.IndexOf(ExtString) > -1 then

or you can loop through an array using .Split(',')

或者您可以使用 .Split(',') 遍历数组