Search code examples
stringdelphidelphi-7

How to delete numbers in the string of Delphi letters


I have a string, I set the coordinates for the selection of letters, but sometimes they mix up and I asked the coordinates with the numbers, how do I make that if for example '105DYUDXB28DYU13' had it done 'DYUDXBDYU'

tmpT.Put:=Trim(MidStr(S,8,6))+Trim(MidStr(S,37,3));

enter image description here


Solution

  • A solution with good performance is as follows (uses Character):

    function RemoveNumbers(const AString: string): string;
    var
      i, j: integer;
    begin
      SetLength(result, AString.Length);
      j := 0;
      for i := 1 to AString.Length do
        if not AString[i].IsDigit then
        begin
          inc(j);
          result[j] := AString[i];
        end;
      SetLength(result, j);
    end;
    

    This function uses a few language and library features introduced after Delphi 7. To make this work in Delphi 7, you need to rewrite it slightly:

    function RemoveNumbers(const AString: string): string;
    var
      i, j: integer;
    begin
      SetLength(result, Length(AString));
      j := 0;
      for i := 1 to Length(AString) do
        if not (AString[i] in ['0'..'9']) then
        begin
          inc(j);
          result[j] := AString[i];
        end;
      SetLength(result, j);
    end;
    

    The fine print: TCharHelper.IsDigit is Unicode-aware, and so it will return true for all Unicode digits. For instance, it will return true for

    • ٣ (U+0663: ARABIC-INDIC DIGIT THREE),
    • ੪ (U+0A6A: GURMUKHI DIGIT FOUR),
    • ௫ (U+0BEB: TAMIL DIGIT FIVE),
    • ៥ (U+17E5: KHMER DIGIT FIVE), and
    • ᠗ (U+1817: MONGOLIAN DIGIT SEVEN).

    If you only want to treat the characters '0'..'9' as digits, you can use the modernized version of the Delphi 7 test:

    if not CharInSet(AString[i], ['0'..'9']) then