数组 – Delphi检查字符是否在’A’范围内.’Z’和’0′..’9′
发布时间:2020-12-15 09:21:28 所属栏目:大数据 来源:网络整理
导读:我需要检查字符串是否只包含范围中的字符:’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 :=
我需要检查字符串是否只包含范围中的字符:’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; 但是,例如,如果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; 请注意,在函数中,如果aValue包含空格字符 – 例如“测试值” – 会引发异常,因此在if语句之后使用Trim是无用的. 像^ [0-9a-zA-Z]这样的正则表达式可以在我看来以更优雅的方式解决您的问题. 编辑 if not Result[i].IsLetterOrDigit then raise Exception.Create('Non valido'); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |