[英]How do I check whether a string exists in an array?
我有這段代碼:
var
ExtString: string;
const
Extensions : array[0..4] of string = ('.rar', '.zip', '.doc', '.jpg', '.gif');
if ExtString in Extensions then
在最后一行,我得到一個錯誤:
[DCC 錯誤] E2015 運算符 ('then') 不適用於此操作數類型
我想我不能這樣做,那么我怎樣才能正確地完成我的任務呢?
正如您發現的那樣,您無法使用in
來檢查字符串數組中的字符串。
您可以使用此 function 代替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;
你可以這樣稱呼它。
if StrInArray(ExtString,Extensions) then
StrUtils.pas
已經定義了這個。
function MatchStr(const AText: string; const AValues: array of string): Boolean;
從常量數組初始化一個 TStringList 實例並使用 IndexOf()。
您可以使用System.StrUtils
中的函數IndexStr
(區分大小寫)或IndexText
(不區分大小寫)在數組中查找字符串並檢索索引。
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');
有時最簡單的解決方案並不是最明顯的
var
ExtString: string;
const
Extensions = ('.rar,.zip,.doc,.jpg,.gif');
if Pos(ExtString, Extensions) > 0 then
或者在我喜歡的新 StrUtils 庫中使用 .Netrification !!! 想想幫手!
if Extensions.IndexOf(ExtString) > -1 then
或者您可以使用.Split(',') 遍歷數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.