Bug in StringReplace (Handling Null characters) (fixed) (Views: 101)


I've noticed a problem when you try to use StringReplace on a string which contains NULL (#0) characters (not null terminated).


There is an undocumented bug in the StringReplace function.

It appears that it does not handle strings will NULL (#0) characters in them.

Here is a better routine which handles NULL correctly.

function customStringReplace(OriginalString, Pattern, Replace: string): string;


  Procedure: customStringReplace
  Date:      07-Feb-2002
  Arguments: OriginalString, Pattern, Replace: string
  Result:    string
    Replaces Pattern with Replace in string OriginalString.
    Taking into account NULL (#0) characters.
    I cheated. This is ripped almost directly from Borland's
    StringReplace Function. The bug creeps in with the ANSIPos
    function. (Which does not detect #0 characters)


    SearchStr, Patt, NewStr: string;
    Offset: Integer;
    Result := '';
    SearchStr := OriginalString;
    Patt := Pattern;
    NewStr := OriginalString;
    while SearchStr <> '' do
      Offset := Pos(Patt, SearchStr); // Was AnsiPos
      if Offset = 0 then
        Result := Result + NewStr;
      Result := Result + Copy(NewStr, 1, Offset - 1) + Replace;
      NewStr := Copy(NewStr, Offset + Length(Pattern), MaxInt);
      SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);

<< Back to main page