I'd like to know how I can delete numbers from a String. I try to use StringReplace and I don't know how to tell the function that I want to replace numbers.
Here's what I tried:
StringReplace(mString, [0..9], '', [rfReplaceAll, rfIgnoreCase]);
I'd like to know how I can delete numbers from a String. I try to use StringReplace and I don't know how to tell the function that I want to replace numbers.
Here's what I tried:
StringReplace(mString, [0..9], '', [rfReplaceAll, rfIgnoreCase]);
Simple but effective. Can be optimized, but should get you what you need as a start:
function RemoveNumbers(const aString: string): string;
var
C: Char;
begin
Result := '';
for C in aString do begin
if not CharInSet(C, ['0'..'9']) then
begin
Result := Result + C;
end;
end;
end;
Pretty quick inplace version.
procedure RemoveDigits(var s: string);
var
i, j: Integer;
pc: PChar;
begin
j := 0;
pc := PChar(@s[1]);
for i := 0 to Length(s) - 1 do
if pc[i] in ['0'..'9'] then
//if CharInSet(pc[i], ['0'..'9']) for Unicode version
Inc(j)
else
pc[i - j] := pc[i];
SetLength(s, Length(s) - j);
end;
This has the same output as Nick's version, but this is more than 3 times as fast with short strings. The longer the text, the bigger the difference.
function RemoveNumbers2(const aString: string): string;
var
C:Char; Index:Integer;
begin
Result := '';
SetLength(Result, Length(aString));
Index := 1;
for C in aString do
if not CharInSet(C, ['0' .. '9']) then
begin
Result[Index] := C;
Inc(Index);
end;
SetLength(Result, Index-1);
end;
Don't waste precious CPU cycles if you don't have to.
Well I was tired of looking for already build functions so I've create my own:
function RemoveNumbers(const AValue: string): string;
var
iCar : Integer;
mBuffer : string;
begin
mBuffer := AValue;
for iCar := Length(mBuffer) downto 1 do
begin
if (mBuffer[iCar] in ['0'..'9']) then
Delete(mBuffer,iCar,1);
end;
Result := mBuffer;
end;
use this
function RemoveNonAlpha(srcStr : string) : string;
const
CHARS = ['0'..'9'];
var i : integer;
begin
result:='';
for i:=0 to length(srcStr) do
if (srcstr[i] in CHARS) then
result:=result+srcStr[i];
end ;
you can call it like this
edit2.text:=RemoveNonAlpha(edit1.text);
StringReplace does not accept a set as the second argument. Maybe someone will have a more suitable approach, but this works:
StringReplace(mString, '0', '', [rfReplaceAll, rfIgnoreCase]);
StringReplace(mString, '1', '', [rfReplaceAll, rfIgnoreCase]);
StringReplace(mString, '2', '', [rfReplaceAll, rfIgnoreCase]);
etc.