2011-06-12 71 views
12

我有這樣的代碼:如何檢查數組中是否存在字符串?

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

if ExtString in Extensions then 

就上線,我得到一個錯誤:

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

我想我不能做到這一點,所以我怎麼能正確地執行我的任務?

+0

**在**運算符不適用於這些操作數類型 – 2011-06-12 04:07:03

+1

這是解釋爲什麼OP的嘗試不起作用,但它不是真正的答案,因爲問題是「我該如何正確執行此任務?」 – jpfollenius 2011-06-12 10:01:23

+0

[查找字符串是否在列表中(沒有泛型)]的最佳方法](http://stackoverflow.com/questions/246623/best-way-to-find-if-a-string-is-不含泛型的列表) – 2016-12-01 22:25:58

回答

18

正如您發現無法使用in檢查字符串數組中的字符串。

您可以使用此功能而不是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; 
+4

+1表示MatchStr,但不幸命名。它應該是一個名詞而不是動詞。我必須說我不是新退出語法的粉絲。但是如果你打算使用它,你不應該一直使用它。在同一例程中使用result和exit()會導致解析變得更加困難。 – 2011-06-12 06:15:54

+3

請注意區分大小寫。文件系統不區分大小寫,你可以找到很多帶.JPG擴展名的文件。上面的代碼將錯過這個。 – Misha 2011-06-12 09:10:52

+1

@Misha:這就是'MatchText'的用途。在一些Delphi版本中,它只作爲'AnsiMatchText'(也許''WideStrings.pas'中的'WideMatchText')存在。 – afrazier 2011-06-15 19:36:45

8

從常量數組​​初始化TStringList實例並使用IndexOf()。

+2

太重,簡單的循環更好 – 2011-06-12 06:07:56

+1

如果頻繁完成並且TStringList持久化,則不是。誰知道這可能會用於什麼? – Misha 2011-06-12 06:30:02

+1

使字符串列表持久化並放棄線程安全。即使如此,你必須分配給沒有意義的字符串列表。 Loop最好不用問。字符串列表是大錘破解堅果。 – 2011-06-12 06:39:29

相關問題