2014-02-18 293 views
3

我試圖找出如果字符串是「助記類型」... 我的助記符類型由字母從'一'到'Z',從'A'到'Z' ,從'0'到'9'的數字,以及另外的'_'。 我構建如下代碼。如果給出的字符串匹配我的助記符模式,則結果應爲True False:德爾福 - 通過字符串循環

TRes := True; 
for I := 0 to (AString.Length - 1) do 
begin 
    if not ((('0' <= AString[I]) and (AString[I] <= '9')) 
     or (('a' <= AString[I]) and (AString[I] <= 'z')) 
     or (('A' <= AString[I]) and (AString[I] <= 'Z')) 
     or (AString[I] = '_')) then 
     TRes := False; 
end; 

此代碼總是以False結果。

回答

9

我假設自從您標記問題XE5並使用從零開始的索引後,您的字符串是從零開始的。但也許這個假設是錯誤的。

你的邏輯很好,雖然它很難閱讀。問題中的代碼已經在做你想要的。至少if聲明確實執行你打算的測試。

讓我們重新編寫代碼,使其更易於理解。我要我們的不同打好它,並使用本地循環變量來表示每個字符:

for C in AString do 
begin 
    if not (
     (('0' <= C) and (C <= '9')) // C is in range 0..9 
    or (('a' <= C) and (C <= 'z')) // C is in range a..z 
    or (('A' <= C) and (C <= 'Z')) // C is in range A..Z 
    or (C = '_')     // C is _ 
) then 
    TRes := False; 
end; 

如果這樣寫,我敢肯定,你會同意,它執行的是你打算測試。

爲了使代碼更易於但是務必要了解,我會寫一個IsValidIdentifierChar功能:

function IsValidIdentifierChar(C: Char): Boolean; 
begin 
    Result := ((C >= '0') and (C <= '9')) 
      or ((C >= 'A') and (C <= 'Z')) 
      or ((C >= 'a') and (C <= 'z')) 
      or (C = '_'); 
end; 

由於@TLama說,你可以寫IsValidIdentifierChar更簡明使用CharInSet

function IsValidIdentifierChar(C: Char): Boolean; 
begin 
    Result := CharInSet(C, ['0'..'9', 'a'..'z', 'A'..'Z', '_']); 
end; 

然後你可以在此功能之上構建您的循環:

TRes := True; 
for C in AString do 
    if not IsValidIdentifierChar(C) do 
    begin 
    TRes := False; 
    break; 
    end; 
+3

或者'Result:= CharInSet(C,['0'..'9','a'..'z','A'..'Z','_');'instead這個醜陋的運營商:) – TLama

+0

我錯過了{$ ZEROBASEDSTRINGS}。感謝其餘的評論。 –

+0

是的,我只是假設你是在一個移動平臺上。應該更加小心。 for in loop是你的朋友! –

5

字符串類型是基於1的。動態數組是基於0的。更好地用於......因此您對未來的德爾福的安全。

測試可能的字符值的範圍可以更有效地完成(更簡潔)是CharInSet。

function IsMnemonic(AString: string): Boolean; 
var 
    Ch: Char; 
begin 
    for Ch in AString do 
    if not CharInSet(Ch, [ '_', '0'..'9', 'A'..'Z', 'a'..'z' ]) then 
     Exit(False); 
    Result := True; 
end; 
+1

字符串也可以爲零,['$ ZEROBASEDSTRINGS ON'](http://docwiki.embarcadero.com/RADStudio/en /零based_strings_(DELPHI))。 –

+0

這是XE5。我的假設是我們使用零基字符串。也許那對我來說太天真了。 –

+0

@LU RD,這就是爲什麼for in是更好的解決方案。我認爲XE5套件中的每個編譯器都不支持基於0/1的選項(但可能是錯誤的)。 –