Delete numbers from a String

2019-03-26 00:53发布

问题:

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]);

回答1:

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;


回答2:

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;


回答3:

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.



回答4:

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;


回答5:

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);



回答6:

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.