Replacing ranges of characters contained within a string
Should it become necessary to replace the values stored in a string, regardless of contents, Tcl has provided the replace
keyword.
The syntax of the string
command is as follows:
string replace string first last replacement
How to do it…
In the following example, we will replace the characters stored in a string with new values. Return values from the commands are provided for clarity. Enter the following command:
% string replace abcdefg 2 5 123456789 ab123456789g
How it works…
Tcl has returned a new string containing the characters located within the index range, from 2
to 5
. This illustrated not only the replacement of the characters, but also the command's ability to create strings that differ in size from the original string. If your program requires that the string, when altered, should be of the same length as the original, care should be taken to avoid this alteration. The string
command reads the value stored in string
and replaces...