user6548546
user6548546

Reputation:

Turbo Pascal: Replace character in String with other character

As its said in the title, im writing a really simple encoding and decoding program with turbo pascal for school and im having trouble finding a solution to replace certain characters in a string.

Thx for the help

Upvotes: 0

Views: 5080

Answers (1)

MartynA
MartynA

Reputation: 30735

As this is homework, I'm not going to give you code that does it, but rather explain how to do it using TP's string-processing facilities. It's years since I had a working copy of TP installed, but from memory:

The key thing about a String in TP is that it can be declared with a maximum length of 255 and is effectively an array of these characters (numbered 1.. max) preceded by a "length" byte which indicates the current number of characters in the string.

So, if you have this declaration

var S : String[20];

you can do an assignment like this

S := 'Hello World';

and you can access the individual characters as

S[1]

whose value is 'H',

S[2]

which is 'e' etc. Never assume anything about the characters beyond the current length of the string as returned by the Length() function.

So, to replace a substring in a string, one way is to

  1. Find the position of the substring in the string. You can use TP's Pos() function for this.

  2. If Pos() finds the substring, it will return a positive integer, otherwise 0. Let's call the return value P.

  3. If P is greater than zero you can use TP's Delete() procedure to delete a specified number of characters from the string, starting at a specified position. So, you would call Delete on your string, passing P as the starting position and Length(SubString) as the number of chars to delete.

  4. Then you can use TP's Insert procedure to insert the replacement substring, starting at P, the position where the original substring was found.

  5. The above steps are for replacing a substring of arbitrary length by another which may differ in length or even be empty (in which case, just omit the Insert() call. In a situation where you want to do a one-for-one replacement of one single character in the string by another single one, you can do it by direct assignment, as in

    S[2] := S[1];

so S becomes 'HHllo World'

or

S[1] := 'A';

Upvotes: 3

Related Questions