string(n)
β¨ string(n) β¨
Tcl Built-In Commands, bestie. No cap, this one is all about making strings do tricks. π
π NAME π
string β Manipulate strings. Periodt.
πΈ SYNOPSIS πΈ
string option arg ?arg ...?
π¦ DESCRIPTION π¦
Okay so string performs one of several string operations, depending on option. The legal options (which may be abbreviated, iykyk) are:
string cat ?string1? ?string2...?β Smushes all the given strings together like they're holding hands and gives you back the combined string. No strings? You get an empty string, periodt. This one is sometimes easier than just putting strings next to each other when you're doing mixed quoting, or when you wanna return a concatenation without usingreturn -level 0, and it's more efficient than making a list of args and usingjoinwith an empty join string. Slay. πstring compare ?-nocase? ?-length length? string1 string2β Does a character-by-character comparison ofstring1andstring2. You get-1,0, or1depending on whetherstring1is lexicographically less than, equal to, or greater thanstring2. If-lengthis specified, only the firstlengthcharacters get compared. If-lengthis negative, it's ignored. If-nocaseis specified, the comparison is case-insensitive. Easy. β¨string equal ?-nocase? ?-length length? string1 string2β Does a character-by-character comparison ofstring1andstring2. Returns1if they're identical, or0if not. If-lengthis specified, only the firstlengthcharacters get compared. If-lengthis negative, it's ignored. If-nocaseis specified, the comparison is case-insensitive. π«Άstring first needleString haystackString ?startIndex?β SearcheshaystackStringfor a sequence of characters that exactly matchneedleString. If it finds one, it returns the index of the first character in the first match insidehaystackString. If not found, you get-1. IfstartIndexis specified (in any of the forms described in STRING INDICES), the search starts with the character inhaystackStringspecified by that index. For example,
string first a 0a23456789abcdef 5
will return 10, but
string first a 0123456789abcdef 11
will return -1.
string index string charIndexβ Gives you thecharIndex'th character of thestringargument. AcharIndexof0is the first character.charIndexcan be specified as described in STRING INDICES. IfcharIndexis less than0or greater than or equal to the length of the string, you get an empty string back. πstring insert string index insertStringβ Returns a copy ofstringwithinsertStringinserted at theindex'th character. Theindexcan be specified as described in STRING INDICES. Ifindexis start-relative, the first character inserted in the returned string will be at the specified index. Ifindexis end-relative, the last character inserted in the returned string will be at the specified index. Ifindexis at or before the start ofstring(e.g.,indexis0),insertStringis prepended tostring. Ifindexis at or after the end ofstring(e.g.,indexisend),insertStringis appended tostring.string is class ?-strict? ?-failindex varname? stringβ Returns1ifstringis a valid member of the specified character class, otherwise0. If-strictis specified, an empty string returns0; otherwise an empty string returns1on any class. If-failindexis specified, then if the function returns0, the index in the string where the class stopped being valid gets stored in the variable namedvarname. Thevarnamewon't be set if the check returns1. The following character classes are recognized (and yes, the class name can be abbreviated):alnumβ Any Unicode alphabet or digit character. No cap.alphaβ Any Unicode alphabet character.asciiβ Any character with a value less than\u0080(those that are in the 7-bit ascii range).booleanβ Any of the forms allowed toTcl_GetBoolean.controlβ Any Unicode control character.dictβ Any proper dict structure, with optional surrounding whitespace. In case of improper dict structure,0is returned and thevarnamewill contain the index of the βelementβ where the dict parsing fails, or-1if this cannot be determined.digitβ Any Unicode digit character. Note that this includes characters outside of the[0-9]range.doubleβ Any of the forms allowed toTcl_GetDoubleFromObj.entierβ Synonym forinteger.falseβ Any of the forms allowed toTcl_GetBooleanwhere the value is false.graphβ Any Unicode printing character, except space.integerβ Any of the valid string formats for an integer value of arbitrary size in Tcl, with optional surrounding whitespace. The formats accepted are exactly those accepted by the C routineTcl_GetBignumFromObj.listβ Any proper list structure, with optional surrounding whitespace. In case of improper list structure,0is returned and thevarnamewill contain the index of the βelementβ where the list parsing fails, or-1if this cannot be determined.lowerβ Any Unicode lower case alphabet character.printβ Any Unicode printing character, including space.punctβ Any Unicode punctuation character.spaceβ Any Unicode whitespace character, mongolian vowel separator (U+180e), zero width space (U+200b), word joiner (U+2060) or zero width no-break space (U+feff) (=BOM).trueβ Any of the forms allowed toTcl_GetBooleanwhere the value is true.upperβ Any upper case alphabet character in the Unicode character set.wideintegerβ Any of the valid forms for a wide integer in Tcl, with optional surrounding whitespace. In case of overflow in the value,0is returned and thevarnamewill contain-1.wordcharβ Any Unicode word character. That is any alphanumeric character, and any Unicode connector punctuation characters (e.g. underscore).xdigitβ Any hexadecimal digit character ([0-9A-Fa-f]).
In the case of boolean, true and false, if the function will return 0, then the varname will always be set to 0, due to the varied nature of a valid boolean value.
string last needleString haystackString ?lastIndex?β SearcheshaystackStringfor a sequence that exactly matchesneedleString. If it finds one, it returns the index of the first character in the last such match insidehaystackString. If there's no match, you get-1. IflastIndexis specified (in any of the forms described in STRING INDICES), only the characters inhaystackStringat or before thatlastIndexare considered. For example,
string last a 0a23456789abcdef 15
will return 10, but
string last a 0a23456789abcdef 9
will return 1.
string length stringβ Returns a decimal string giving the number of characters instring. Note that this isn't necessarily the same as the number of bytes used to store the string. If the value is a byte array value (like the ones you get from reading a binary encoded channel), then this returns the actual byte length of the value. πstring map ?-nocase? mapping stringβ Replaces substrings instringbased on the key-value pairs inmapping.mappingis a list of key value key value ... just like the form returned byarray get. Every instance of a key in the string gets replaced with its corresponding value. If-nocaseis specified, matching ignores case differences. Both key and value can be multiple characters. Replacement happens in an ordered manner, so the key appearing first in the list gets checked first, and so on.stringis only iterated over once, so earlier key replacements won't affect later key matches. For example,
string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
will return the string 01321221.
Note that if an earlier key is a prefix of a later one, it completely masks the later one. So if the previous example is reordered like this,
string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
it will return the string 02c322c222c.
string match ?-nocase? pattern stringβ See ifpatternmatchesstring; return1if it does,0if it doesn't. If-nocaseis specified, the pattern tries to match against the string in a case insensitive manner. For the two strings to match, their contents must be identical except that the following special sequences can appear inpattern:*β Matches any sequence of characters instring, including a null string.?β Matches any single character instring.
[chars]β matches any single character that lives in the set chars. And bestie, if you write something like x-y inside chars, that's a range β everything from x to y, both ends included, matches. π But here's the plot twist: when you're running with-nocase, the endpoints of that range get converted to lowercase first. So{[A-z]}will happily match"_"when you're matching case-sensitively (because"_"sits right between"Z"and"a"in the character order, messy ik), but with-nocaseit's treated like{[A-Za-z]}β which is lowkey what you meant the whole time. π\xβ matches just the single character x, nothing more. This is the escape hatch π«Ά for when you need to dodge the special meaning of the characters*?[]\in a pattern. It's giving "let me just say the literal thing, please." β¨
string range string first lastβ hands you a chunk of consecutive characters from string, kicking off at the character whose index is first and wrapping up at the character whose index is last (using all the forms from STRING INDICES, we'll get there π). Index0= the very first character of the string; indexend= the very last one. Both first and last can be written the way you'd write them for the index method. If first is less than zero it's treated like it was zero, and if last is greater than or equal to the length of the string it's treated like it wasend. And if first is greater than last? You get an empty string back. Nothing. Nada. πstring repeat string countβ returns string glued to itself count times. If count is0, you get the empty string back. That's it, that's the whole vibe. πstring replace string first last ?newstring?β deletes a range of consecutive characters from string, starting at the character with index first and ending at the character with index last (forms from STRING INDICES, as always β¨). Index0= the first character of the string. First and last can be written like you would for the index method. If you pass newstring, it gets dropped in right where that removed range used to be β glow-up in real time π . If first is less than zero it's treated as zero, and if last is greater than or equal to the length of the string it's treated asend. The original string comes back completely untouched if first is greater than last, or if first is equal to or greater than the length of the initial string, or if last is less than0. Untouched, unbothered, thriving. πstring reverse stringβ returns a string the same length as string but with the characters in reverse order. Backwards, but make it fashion. πstring tolower string ?first? ?last?β same value as string, except every upper (or title) case letter got converted to lowercase. If first is specified, it's the first char index where the modifying starts. If last is specified, it's the char index to stop at β inclusive, bestie. Both first and last can use the forms from STRING INDICES. πΈstring totitle string ?first? ?last?β same value as string, except the first character in string gets converted to its Unicode title case variant (or upper case if there's no title case variant available, no biggie) and the rest of the string gets converted to lowercase. If first is specified, that's the first char index where modifying begins. If last is specified, that's the char index to stop at, inclusive. first and last may be given using the forms in STRING INDICES. Title case = main character energy, obviously. πβ¨string toupper string ?first? ?last?β same value as string, except all the lower (or title) case letters got converted to uppercase. If first is specified, it's the first char index where modifying starts. If last is specified, it's the char index to stop at, inclusive. first and last may be specified using the forms in STRING INDICES. LOUD AND PROUD π£string trim string ?chars?β same value as string, except any leading or trailing characters that show up in the string chars get removed. If chars isn't specified, whitespace gets removed instead β that means any character for whichstring is spacereturns1, plus"\0". π§Ήβ¨string trimleft string ?chars?β same value as string, except any leading characters present in chars get removed. If chars isn't specified, whitespace is what gets removed (any character for whichstring is spacereturns1, and"\0"). Left side only, bestie. π«²string trimright string ?chars?β same value as string, except any trailing characters present in chars get removed. If chars isn't specified, whitespace gets removed (any character for whichstring is spacereturns1, and"\0"). Right side only. π«±
π« OBSOLETE SUBCOMMANDS
These subcommands are currently supported, but heads up β they're likely to go away in a future release, because their functionality is either basically never used or straight up misleading. Not me warning you in advance π
string wordend string charIndexβ returns the index of the character just after the last one in the word that contains the character at charIndex of string. charIndex may be specified using the forms in STRING INDICES. A "word" here counts as any contiguous range of alphanumeric characters (Unicode letters or decimal digits) or underscore (Unicode connector punctuation), or any single character that isn't one of those. π§string wordstart string charIndexβ returns the index of the first character in the word containing the character at charIndex of string. charIndex may be specified using the forms in STRING INDICES. Same word definition: any contiguous range of alphanumeric (Unicode letters or decimal digits) or underscore (Unicode connector punctuation) characters, or any single character that isn't one of those. π
π’ STRING INDICES
Whenever you're referring to indices into a string (like for string index or string range), these formats are supported, bestie:
- integer β for any index value that passes
string is integer -strict, the char sitting at that integral index. Like,2would point at the"c"in"abcd". π₯ - end β the last char of the string. So
endwould point at the"d"in"abcd". π - end-N β the last char of the string minus the specified integer offset N. So
"end-1"would point at the"c"in"abcd". β¨ - end+N β the last char of the string plus the specified integer offset N. So
"end+-1"would point at the"c"in"abcd". Yes, that's literally how it's written. π«Ά - M+N β the char at the integral index that is the sum of the integer values M and N. So
"1+1"would point at the"c"in"abcd". π - M-N β the char at the integral index that is the difference of the integer values M and N. So
"2-1"would point at the"b"in"abcd". π
In the specs above, the integer value M has no trailing whitespace, and the integer value N has no leading whitespace. Keep it clean, okay? π§Ό
β¨ EXAMPLE
Wanna test whether the string in the variable string is a proper non-empty prefix of the string foobar? Iconic. Here's the move:
set length [string length $string]
if {$length == 0} {
set isPrefix 0
} else {
set isPrefix [string equal -length $length $string "foobar"]
}
π SEE ALSO
π KEYWORDS
case conversion, compare, index, integer value, match, pattern, string, word, equal, ctype, character, reverse
okay bestie that's the whole page, you ate that π this was Tcl 8.1, string(n) β go forth and manipulate some strings, no cap. π¦πΈπ
π¦ where this page comes from
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms