Reputation: 12163
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.
Upvotes: 9
Views: 9248
Reputation: 136391
try this code to check if a char is a alphabetical character.
MyStr:='[-Bobby-]';
//is an alphabetical character ?
if MyStr[1] in ['a'..'z','A'..'Z'] then
to remove from a string all the non alphabetical characters (English characters) you can use something like this.
NewStr:='';
for i := 1 to Length(MyStr) do
if MyStr[i] in ['a'..'z','A'..'Z'] then
NewStr:=NewStr+MyStr[i];
now the NewStr
variable only contains alphabetical characters.
in newer versions of delphi you can use the Character.IsLetter
function.
Upvotes: 6
Reputation: 3983
Perfect Solution:
Result := TRegEx.Replace('Input12231213','[^a-zA-Z]+',''); // Result = 'Input'
Works in Delphi XE
Upvotes: 0
Reputation: 1826
I have a whole suite of optimised string routines to do this stuff, which work with both Unicode and non-Unicode Delphi. The two most relevant ones are:
function CsiRemoveArgs(const pInStr: string; const pArgs: string;
pRestrictToArgs: Boolean = False): string;
function CsiRemoveArgs(const pInStr: string; pArgs: TSysCharSet;
pRestrictToArgs: Boolean = False): string;
You can download them here.
Upvotes: 1
Reputation: 108948
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;
Upvotes: 16