简体   繁体   English

从字符串中删除数字

[英]Delete numbers from a String

I'd like to know how I can delete numbers from a String. 我想知道如何从String中删除数字。 I try to use StringReplace and I don't know how to tell the function that I want to replace numbers. 我尝试使用StringReplace,我不知道如何告诉函数我想要替换数字。

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. 相当快速的inplace版本。

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. 这与Nick的版本具有相同的输出,但这是短字符串的3倍以上。 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. 如果您不必浪费宝贵的CPU周期,请不要浪费。

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); edit2.text:= RemoveNonAlpha(edit1.text);

StringReplace does not accept a set as the second argument. StringReplace不接受set作为第二个参数。 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. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM