Tcl Tutorial Lesson 17

String Subcommands - length index range

Tcl commands often have "subcommands". The string command is an example of one of these. The string command treats its first argument as a subcommand. Utilizing subcommands is a good way to make one command do multiple things without using cryptic names. For instance, Tcl has string length instead of, say, slength.

Here we cover these string subcommands:

string length str
Returns the length of str.
string index str i
Returns the i'th character from str.
string range str first last
Returns a string composed of the characters from first to last taken from str.


set string "this is my test string"

puts "There are [string length $string] characters in \"$string\""

puts "[string index $string 1] is the second character in \"$string\""
puts "Second character in \"$string\"" is [string index $string 1]"

puts "Substring from 5th to 10th: \"[string range $string 5 10]\""

  Resulting output
There are 22 characters in "this is my test string"
Second character in "this is my test string" is h
Substring from 5th to 10th: "is my"