检查MyString [1]是否是字母字符?

Jef*_*eff 7 delphi string character char

我有一个字符串,让我们调用它MyStr.我试图摆脱字符串中的每个非字母字符.就像在IM中像MSN和Skype一样,人们将他们的显示名称设置为[-Bobby-].我想删除该字符串中不是字母字符的所有内容,所以我留下的就是"名称".

我怎么能在Delphi中做到这一点?我正在考虑创建一个TStringlist并在那里存储每个有效字符,然后IndexOf用来检查char是否有效,但我希望有一个更简单的方法.

And*_*and 15

最简单的方法是

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;
Run Code Online (Sandbox Code Playgroud)

但这只会将英文字母视为"字母字符".它甚至不会将极其重要的瑞典字母Å,Ä和Ö视为"字母字符"!

稍微复杂一点

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;
Run Code Online (Sandbox Code Playgroud)

  • 在第一种方法中,您可以将它们添加到集合中("Æ","Ø","Å","Ä","Ö","å","ä","ö").后一种方法,使用`IsLetter`,将自动包含所有语言的所有字母. (2认同)

RRU*_*RUZ 5

尝试此代码以检查char是否是字母字符.

  MyStr:='[-Bobby-]';
  //is an alphabetical character ?
  if MyStr[1] in ['a'..'z','A'..'Z'] then
Run Code Online (Sandbox Code Playgroud)

要从字符串中删除所有非字母字符(英文字符),您可以使用这样的字符.

NewStr:='';
for i := 1 to Length(MyStr) do
 if MyStr[i] in ['a'..'z','A'..'Z'] then
   NewStr:=NewStr+MyStr[i];
Run Code Online (Sandbox Code Playgroud)

现在NewStr变量只包含字母字符.

在较新版本的delphi中,您可以使用该Character.IsLetter功能.

  • @jeroen,答案说``从字符串中删除所有非字母字符(英文字符)`以覆盖OP可以使用`Character.IsLetter`函数的其余字母字符,或者只是展开集合像andreas这样的额外字符在内容中解释. (3认同)