String Handling Fundamentals
In Tcl, every value is fundamentally a string, even lists and numbers are strings that happen to have a well-formed list or numeric representation, which is why the string command ensemble is one of the most heavily used commands in the language. string is a single command with dozens of subcommands (string length, string index, string range, and so on), invoked as string subcommand arg ..., following the same ensemble pattern used by array, dict, and info. Because strings are Tcl's universal currency, mastering string subcommands is essential for everything from input validation to text processing.
Cricket analogy: Just as every scoreline, player name, and match date on a cricket scorecard is ultimately printed text regardless of what it represents, every Tcl value is fundamentally a string -- a score of 250 and a team name 'India' are both just text until something interprets them as a number or an identifier.
Common string Subcommands
string length $s returns the character count, string index $s $i returns the single character at position $i (zero-indexed), and string range $s $start $end extracts a substring, with end as a valid keyword meaning the last character. Case conversion is handled by string tolower, string toupper, and string totitle, while string trim, string trimleft, and string trimright strip whitespace, or a specified character set, from the ends of a string, useful for cleaning up user input before further processing.
Cricket analogy: string range $commentary 0 49 pulling the first 50 characters of a live commentary feed is like a highlights editor trimming a broadcast transcript down to the opening line, and string trim stripping stray whitespace from a scraped scorecard mirrors cleaning up messy data before display.
Searching and Pattern Matching
string match pattern string performs glob-style matching using *, ?, and [...] wildcards and returns 1 or 0, which is handy for quick pattern checks without the overhead of a full regular expression. string first needle haystack returns the index of the first occurrence of needle in haystack, or -1 if not found, while string last searches from the end. For anything more complex than glob patterns, capturing groups, alternation, quantifiers, the regexp command (and its substitution counterpart regsub) supports full POSIX-extended regular expressions, e.g. regexp {(\d+)-(\d+)} $s -> a b captures two numeric groups into variables a and b.
Cricket analogy: string match "*century*" $commentaryLine catching any commentary mentioning a century, regardless of surrounding words, mirrors a highlight-clip generator scanning transcripts for key moments, while regexp {(\d+)/(\d+)} $score -> wickets runs mirrors a scorecard parser extracting structured numbers from raw text.
Formatting and Building Strings
format builds strings using C-printf-style specifiers: format "%s scored %d runs" $name $runs substitutes a string and an integer into a template, supporting width, precision, and padding just like printf. append grows a variable's string value in place, append log "\n$entry" is more efficient than set log "$log\n$entry" because it avoids Tcl re-copying the whole string on every call. string repeat $s $n builds a string by repeating $s n times, and string map {from1 to1 from2 to2} $s performs multiple simultaneous substring replacements in one pass.
Cricket analogy: format "%s scored %d off %d balls" $name $runs $balls building a scorecard line mirrors a broadcast graphics template, while append liveLog "\n$ballEvent" growing a ball-by-ball log efficiently mirrors a scoring app appending each delivery without rebuilding the whole log from scratch.
set title "the go programming language"
puts [string totitle $title]
puts [string length $title]
puts [string range $title 4 5]
set line "Player: Kohli, Runs: 82, Balls: 49"
if {[regexp {Runs: (\d+), Balls: (\d+)} $line -> runs balls]} {
set sr [format "%.2f" [expr {double($runs) / $balls * 100}]]
puts "Strike rate: $sr"
}
set log ""
foreach entry {"4 runs" "6 runs" "OUT"} {
append log "$entry\n"
}
puts $logstring is itself an ensemble command -- string length, string match, string map, and dozens more are all subcommands dispatched from one top-level string command, the same design pattern used by array, dict, info, and namespace. You can list every subcommand available in your Tcl version with info commands string or by checking string in an interactive shell with tab completion.
string compare and ==/eq inside expr are not the same thing to confuse: string compare $a $b returns -1, 0, or 1 for use in sorting, while if {$a eq $b} gives you a plain boolean. Also, string match uses glob patterns (*, ?, [...]), not regular expressions -- a pattern like \d+ means nothing special to string match and will only match those literal characters; use regexp when you need real regex quantifiers and capture groups.
- Every Tcl value, including lists and numbers, is fundamentally a string, which is why string is one of the most-used command ensembles in the language.
- string length, string index, and string range handle size, single-character access, and substring extraction respectively, all zero-indexed.
- string tolower, string toupper, string totitle, and the string trim* family handle case conversion and whitespace cleanup.
- string match does glob-style wildcard matching (*, ?, [...]); use regexp for full regular expressions with capture groups.
- string first and string last locate a substring's position, returning -1 if not found.
- format builds strings with printf-style specifiers; append grows a string variable efficiently in place.
- string repeat and string map handle repetition and multi-pattern substitution in a single call.
Practice what you learned
1. What does string match "a*c" "abc" return?
2. Which command should you use to extract capture groups (like two numbers separated by a dash) from a string?
3. Why is append log "\n$entry" generally preferred over set log "$log\n$entry" in a loop?
4. What does format "%05d" 42 produce?
Was this page helpful?
You May Also Like
Procedures in Tcl
Learn how to define reusable commands with proc, including default arguments, variable-arity args, return values, scope, and recursion.
Arrays and Dictionaries in Tcl
Understand Tcl's associative arrays and the modern dict command, and learn when to reach for each key-value structure.
Conditionals in Tcl
Learn how Tcl evaluates branching logic with if/elseif/else, the expr command, comparison operators, and the switch command for multi-way branching.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics