Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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".

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
942 views
Welcome To Ask or Share your Answers For Others

1 Answer

The simplest approach is

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"!

Slightly more sophisticated is

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...