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 it with the value stored in replacement, based on the index values passed in first and last. Note that the replacement may increase or decrease the size of the string as needed, based on the values passed. An index of 0 refers to the first character. If first is a negative number or last is greater than the string length, then Tcl will adjust them to meet the actual start and end of the string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.42.116