Replacing values within a string
Tcl has added a very useful keyword to the string command to simplify alteration of the string. The map
keyword allows us to replace values within a string as passed without having to programmatically locate the target characters.
The syntax of the string
command is as follows:
string map nocase mapping string
The string
command will read the mapping provided and replace the affected values within the string. Mapping is passed as a valid Tcl list in a key-value pair format similar to that returned by performing a get
on an array. Bear in mind that the string is only mapped once. If the optional nocase
switch is provided, a case insensitive match will be made.
How to do it…
In the following example, we will replace every instance of a character set inside a string. Return values from the commands are provided for clarity. Enter the following command:
% string map {abc def} abcabcabc defdefdef
How it works…
Tcl has mapped each occurrence of the string "abc" and...