William Ward
William Ward

Reputation: 23

Manual String Replace (Free Pascal)

I am trying to replace a word in a string without using StringReplace, any idea how?

I am using 4 text boxes.

1st box is original text 2nd box is the search word 3rd box is the replace word 4rd box is the outcome text

var
  Form1: TForm1;
  result: string;
  rep: string;
  i, iCount: integer;  


procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit4.Text := StringReplace(Edit1.Text, Edit2.Text, Edit3.Text, [rfReplaceAll, rfIgnoreCase]);
  begin
    result := Edit4.Text;
    rep := Edit3.Text;
    iCount := 0;

    for i := 1 to length(result) do
    begin
      if result[i] = rep then
        inc(iCount);
    end;
  end;
  label5.Caption := ('There was ' + IntToStr(iCount) + ' changes made');
end;  

Upvotes: 2

Views: 3646

Answers (1)

MartynA
MartynA

Reputation: 30735

This should do something like you want:

program mystringreplacetest;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes, SysUtils;


function MyStringReplace(const Input, Find, Replace : String; out Count : Integer) : String;
var
  P : Integer;
begin
  Count := 0;

  Result := Input;

  repeat
    P := Pos(Find, Result);
    if P > 0 then begin
      Delete(Result, P, Length(Find));
      Insert(Replace, Result, P); 
      Inc(Count);
    end;
  until P = 0;
end;


var
  S : String;
  Count : Integer;
begin
  S := 'a cat another cat end';
  S := MyStringReplace(S, 'cat', 'hamster', Count);
  writeln(S, ' : ', Count);
  readln;
end.

In case this is homework, I've left a couple of things for you to do:

  • Case insensitivity

  • Avoiding repeated scanning the characters up to the first occurrence of Find.

Obviously, it would be good if you read up on the Pos function and the Delete and Insert procedures for future reference.

PS: Beware that this code contains a trap for the unwary. Consider what happens when the Replace string contains the Find one (e.g. Find = 'cat' and Replace = 'catflap'). Can you see what the problem would be, and how to avoid it?

Upvotes: 2

Related Questions