Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Find and Replace Type Thing

MoKoMoKoMoKoMoKo Posts: 4Member
'ello all...

Wonder if anyone can help...You know how most word processors and hex editors have a Find and Replace function (where the program searches thru' the file for a given string, and replaces it with a different string) would I be able to implement such a thing in Pascal? For example, get Pascal to open any file and change all occurrences of 'Apple' to 'Orange' or whatever...

Thanx...
Laterz all...
MoKo

Comments

  • ManningManning Posts: 1,621Member
    : 'ello all...
    :
    : Wonder if anyone can help...You know how most word processors and hex editors have a Find and Replace function (where the program searches thru' the file for a given string, and replaces it with a different string) would I be able to implement such a thing in Pascal? For example, get Pascal to open any file and change all occurrences of 'Apple' to 'Orange' or whatever...

    Sure thats possible. I would open 2 files. 1 for input, 1 for output. Read a line from the infile, process it with Replace (see below for function), and write it to the outfile. When you reach the end of the infile, close and delete it. Then rename the outfile to the original name of the infile, and you're done.

    [code]
    { S = The line of text to find/replace in }
    { Old = The text to delete }
    { New = The text to add }
    { Example: Replace('I want an apple', 'apple', orange' }
    { That would return 'I want an orange' }
    { Note..this is done from memory and untested...should work tho }
    function Replace(S, Old, New: String): String;
    begin
    while (Pos(Old, S) > 0) do
    begin
    Insert(New, S, Pos(Old, S));
    Delete(S, Pos(Old, S), Length(Old));
    end;
    Replace := S;
    end;
    [/code]
Sign In or Register to comment.