检查MyString [1]是否为字母字符? [英] Check if MyString[1] is an alphabetical character?
问题描述
我有一个字符串,让它 MyStr
。我试图摆脱字符串中的每个非字母字符。比如,在IM的MSN和Skype,人们把他们的显示名称像 [ - Bobby - ] 。我想删除该字符串中不是字母字符的所有内容,所以我留下的是名称。
I have a string, lets call it MyStr
. I am trying to get rid of every non-alphabetical character in the string. Like, in IM's like MSN and Skype, people put their display names like [-Bobby-]. I would like to remove everything in that string that is not an alphabetical character, so all I am left with, is the "name".
我如何做到这一点德尔福?我正在考虑创建一个 TStringlist
并存储每个有效字符,然后使用 IndexOf
来检查字符
How can I do that in Delphi? I was thinking about creating a TStringlist
and store each valid character in there, and then use IndexOf
to check if the char is valid, but I was hoping for an easier way.
推荐答案
最简单的方法是
function GetAlphaSubstr(const Str: string): string;
const
ALPHA_CHARS = ['a'..'z', 'A'..'Z'];
var
ActualLength: integer;
i: Integer;
begin
SetLength(result, length(Str));
ActualLength := 0;
for i := 1 to length(Str) do
if Str[i] in ALPHA_CHARS then
begin
inc(ActualLength);
result[ActualLength] := Str[i];
end;
SetLength(Result, ActualLength);
end;
但这只会将英文字母视为字母字符。它甚至不会考虑极为重要的瑞典字母Å,Ä和Ö作为字母字符!
but this will only consider English letters as "alphabetical characters". It will not even consider the extremely important Swedish letters Å, Ä, and Ö as "alphabetical characters"!
稍微更复杂的是
function GetAlphaSubstr2(const Str: string): string;
var
ActualLength: integer;
i: Integer;
begin
SetLength(result, length(Str));
ActualLength := 0;
for i := 1 to length(Str) do
if Character.IsLetter(Str[i]) then
begin
inc(ActualLength);
result[ActualLength] := Str[i];
end;
SetLength(Result, ActualLength);
end;
这篇关于检查MyString [1]是否为字母字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!