img*_*one 4 arrays delphi string range
我需要检查字符串是否只包含范围:中的字符'A'..'Z', 'a'..'z', '0'..'9',所以我写了这个函数:
function GetValueTrat(aValue: string): string;
const
number = [0 .. 9];
const
letter = ['a' .. 'z', 'A' .. 'Z'];
var
i: Integer;
begin
for i := 1 to length(aValue) do
begin
if (not(StrToInt(aValue[i]) in number)) or (not(aValue[i] in letter)) then
raise Exception.Create('Non valido');
end;
Result := aValue.Trim;
end;
Run Code Online (Sandbox Code Playgroud)
但是,例如,aValue = 'Hello'该StrToInt函数会引发异常.
一套独特的Char可用于您的目的.
function GetValueTrat(const aValue: string): string;
const
CHARS = ['0'..'9', 'a'..'z', 'A'..'Z'];
var
i: Integer;
begin
Result := aValue.Trim;
for i := 1 to Length(Result) do
begin
if not (Result[i] in CHARS) then
raise Exception.Create('Non valido');
end;
end;
Run Code Online (Sandbox Code Playgroud)
请注意,在函数中,如果aValue包含空格字符('test value '例如),则会引发异常,因此Trim在if语句后使用无用.
^[0-9a-zA-Z]在我看来,正则表达式可以更优雅地解决您的问题.
编辑
根据@ RBA对该问题的评论,System.Character.TCharHelper.IsLetterOrDigit可以用作上述逻辑的替代:
if not Result[i].IsLetterOrDigit then
raise Exception.Create('Non valido');
Run Code Online (Sandbox Code Playgroud)