我假设自从您标记问题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;
或者'Result:= CharInSet(C,['0'..'9','a'..'z','A'..'Z','_');'instead这个丑陋的运营商:) – TLama
我错过了{$ ZEROBASEDSTRINGS}。感谢其余的评论。 –
是的,我只是假设你是在一个移动平台上。应该更加小心。 for in loop是你的朋友! –