Trimming a string
When writing a program, there is no way to ensure that only correctly formatted data is provided. An end-user may inadvertently enter whitespace, a test file may contain whitespaces, and so on. To address this issue, Tcl provides keywords to trim the undesirable whitespaces or characters if specified. The first of these is the trim
keyword.
The syntax of the string
command is as follows:
string trim string characters
If no characters are provided, the trim
keyword will return the string
with all leading and trailing whitespace trimmed. If the characters
are not specified (specifying the characters
is optional), only those whitespaces will be removed.
How to do it…
In the following example, we will trim the .gif
extension from a string. Return values from the commands are provided for clarity. Enter the following command:
% string trim "picture.gif " .gif picture
How it works…
As you can see, Tcl has returned our trimmed string.