检查 MyString[1] 是否是字母字符? [英] Check if MyString[1] is an alphabetical character?
问题描述
我有一个字符串,我们称之为 MyStr
.我试图摆脱字符串中的每个非字母字符.例如,在 MSN 和 Skype 等 IM 中,人们将他们的显示名称设为 [-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".
如何在 Delphi 中做到这一点?我正在考虑创建一个 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屋!