string(3tcl)
β¨ NAME β¨
string β manipulate strings π
(it's a Tcl Built-In Command, bestie, you already know π)
β¨ SYNOPSIS β¨
string option arg ?arg ...?
β¨ DESCRIPTION β¨
Okay so string performs one of several string operations, depending on option. Periodt. π
Following common usage, the command descriptions below use the term character in place of the more accurate term code point. (They're keeping it cute and casual, iykyk.)
The legal options (which may be abbreviated) are:
string cat ?string1? ?string2...?β Concatenate the given strings just like placing them directly next to each other and return the resulting compound string. If no strings are present, the result is an empty string.
This primitive is occasionally handier than juxtaposition of strings when mixed quoting is wanted, or when the aim is to return the result of a concatenation without resorting to return -level 0, and is more efficient than building a list of arguments and using join with an empty join string. Slay. β¨
string compare ?-nocase? ?-length length? string1 string2β Perform a character-by-character comparison of stringsstring1andstring2. Returns-1,0, or1, depending on whetherstring1is lexicographically less than, equal to, or greater thanstring2. If-lengthis specified, then only the firstlengthcharacters are used in the comparison. If-lengthis negative, it is ignored. If-nocaseis specified, then the strings are compared in a case-insensitive manner. πstring equal ?-nocase? ?-length length? string1 string2β Perform a character-by-character comparison of stringsstring1andstring2. Returns1ifstring1andstring2are identical, or0when not. If-lengthis specified, then only the firstlengthcharacters are used in the comparison. If-lengthis negative, it is ignored. If-nocaseis specified, then the strings are compared in a case-insensitive manner. No cap. π§string first needleString haystackString ?startIndex?β SearchhaystackStringfor a sequence of characters that exactly match the characters inneedleString. If found, return the index of the first character in the first such match withinhaystackString. If not found, return-1. IfstartIndexis specified (in any of the forms described in STRING INDICES), then the search is constrained to start with the character inhaystackStringspecified by the index. For example,
string first a 0a23456789abcdef 5
will return 10, but
string first a 0123456789abcdef 11
will return -1.
string index string charIndexβ Returns thecharIndex'th character of thestringargument. AcharIndexof0corresponds to the first character of the string.charIndexmay be specified as described in the STRING INDICES section.
If charIndex is less than 0 or greater than or equal to the length of the string then this command returns an empty string. (It's giving ghosted. π»)
string insert string index insertStringβ Returns a copy ofstringwithinsertStringinserted at theindex'th character. Theindexmay be specified as described in the STRING INDICES section.
If index is start-relative, the first character inserted in the returned string will be at the specified index. If index is end-relative, the last character inserted in the returned string will be at the specified index.
If index is at or before the start of string (e.g., index is 0), insertString is prepended to string. If index is at or after the end of string (e.g., index is end), insertString is appended to string.
string is class ?-strict? ?-failindex varname? stringβ Returns1ifstringis a valid member of the specified characterclass, otherwise returns0. If-strictis specified, then an empty string returns0, otherwise an empty string will return1on any class. If-failindexis specified, then if the function returns0, the index in the string where the class was no longer valid will be stored in the variable namedvarname. Thevarnamewill not be set ifstringreturns1. The following character classes are recognized (the class name can be abbreviated):alnumβ Any Unicode alphabet or digit character.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?β SearchhaystackStringfor a sequence of characters that exactly match the characters inneedleString. If found, return the index of the first character in the last such match withinhaystackString. If there is no match, then return-1. IflastIndexis specified (in any of the forms described in STRING INDICES), then only the characters inhaystackStringat or before the specifiedlastIndexwill be considered by the search. 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 is not necessarily the same as the number of bytes used to store the string. If the value is a byte array value (such as those returned from reading a binary encoded channel), then this will return the actual byte length of the value.string map ?-nocase? mapping stringβ Replaces substrings instringbased on the key-value pairs inmapping.mappingis a list ofkey value key value ...as in the form returned byarray get. Each instance of akeyin the string will be replaced with its correspondingvalue. If-nocaseis specified, then matching is done without regard to case differences. Bothkeyandvaluemay be multiple characters. Replacement is done in an ordered manner, so the key appearing first in the list will be checked first, and so on.stringis only iterated over once, so earlier key replacements will have no affect for 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 will completely mask 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 does not. If-nocaseis specified, then the pattern attempts 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 may 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 you hand it as chars. And if a sequence shaped likex-yshows up inside chars, that's a range β every character betweenxandy, inclusive, will match. Ngl, that's kind of the whole point. When you're rocking it with-nocase, the endpoints of the range get converted to lower case first. Here's the tea though:{[A-z]}lowkey matches"_"when you're matching case-sensitively (since"_"falls between"Z"and"a"), but with-nocasethat set gets treated like{[A-Za-z]}β which is honestly probably what you meant in the first place. π\xβ matches exactly one character, namelyx. This is your little escape hatch, bestie: it's how you dodge the special interpretation of the characters*?[]\when they show up inside a pattern. Slash first, chaos later. π¦
string range string first last
Returns a range of consecutive characters from string, starting at the character whose index is first and ending at the character whose index is last (all using the forms described down in STRING INDICES). An index of 0 refers to the first character of the string; an index of end refers to the last character of the string. first and last may be specified as for the index method. If first is less than zero then it is treated as if it were zero, and if last is greater than or equal to the length of the string then it is treated as if it were end. And if first is greater than last, you get an empty string back. Nothing. Emptiness. It's giving minimalism. β¨
string repeat string count
Returns a string consisting of string concatenated with itself count times. If count is 0, the empty string will be returned. Zero copies, zero drama.
string replace string first last ?newstring?
Removes a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last (using the forms described in STRING INDICES). An index of 0 refers to the first character of the string. First and last may be specified as for the index method. If newstring is specified, then it is placed in the removed character range. If first is less than zero then it is treated as if it were zero, and if last is greater than or equal to the length of the string then it is treated as if it were end. The initial string is returned untouched, if first is greater than last, or if first is equal to or greater than the length of the initial string, or last is less than 0. No notes, no edits, we leave it exactly how we found it. π
string reverse string
Returns a string that is the same length as string but with its characters in the reverse order. Mirror mirror on the wall. πͺ
string tolower string ?first? ?last?
Returns a value equal to string except that all upper (or title) case letters have been converted to lower case. If first is specified, it refers to the first char index in the string to start modifying. If last is not specified, only the character at position first is converted, otherwise last refers to the char index in the string to stop at (inclusive). first and last may be specified using the forms described in STRING INDICES.
string totitle string ?first? ?last?
Returns a value equal to string except that the first character in string is converted to its Unicode title case variant (or upper case if there is no title case variant) and the rest of the string is converted to lower case. If first is specified, it refers to the first char index in the string to start modifying. If last is not specified, only the character at position first is converted, otherwise last refers to the char index in the string to stop at (inclusive). first and last may be specified using the forms described in STRING INDICES. Title case is that fancy first-letter-slays-and-everyone-else-whispers energy. π
string toupper string ?first? ?last?
Returns a value equal to string except that all lower (or title) case letters have been converted to upper case. If first is specified, it refers to the first char index in the string to start modifying. If last is not specified, only the character at position first is converted, otherwise last refers to the char index in the string to stop at (inclusive). first and last may be specified using the forms described in STRING INDICES. SAY IT LOUDER. π£
string trim string ?chars?
Returns a value equal to string except that any leading or trailing characters present in the string given by chars are removed. If chars is not specified then white space is removed (any character for which string is space returns 1, and "\0"). Shaving off the edges, both sides. πΈ
string trimleft string ?chars?
Returns a value equal to string except that any leading characters present in the string given by chars are removed. If chars is not specified then white space is removed (any character for which string is space returns 1, and "\0"). Left side only, bestie.
string trimright string ?chars?
Returns a value equal to string except that any trailing characters present in the string given by chars are removed. If chars is not specified then white space is removed (any character for which string is space returns 1, and "\0"). Right side only. Balance restored. βοΈ
π OBSOLETE SUBCOMMANDS π
Okay so these subcommands are currently supported, but they're likely to go away in a future release β their functionality is either virtually never used or, and I'm quoting the vibe here, highly misleading. So likeβ¦ don't build your whole personality around them. π©
string wordend string charIndex
Returns the index of the character just after the last one in the word containing character charIndex of string. charIndex may be specified using the forms in STRING INDICES. A word is considered to be any contiguous range of alphanumeric (Unicode letters or decimal digits) or underscore (Unicode connector punctuation) characters, or any single character other than these.
string wordstart string charIndex
Returns the index of the first character in the word containing character charIndex of string. charIndex may be specified using the forms in STRING INDICES. A word is considered to be any contiguous range of alphanumeric (Unicode letters or decimal digits) or underscore (Unicode connector punctuation) characters, or any single character other than these.
β¨ STRING INDICES β¨
When you're referring to indices into a string (like for string index or string range), here's every format that's supported, and yes we're going through all of them:
integerβ For any index value that passesstring is integer -strict, the char specified at this integral index (e.g.,2would refer to the"c"in"abcd").endβ The last char of the string (e.g.,endwould refer to the"d"in"abcd").end-Nβ The last char of the string minus the specified integer offsetN(e.g.,"end-1"would refer to the"c"in"abcd").end+Nβ The last char of the string plus the specified integer offsetN(e.g.,"end+-1"would refer to the"c"in"abcd").M+Nβ The char specified at the integral index that is the sum of integer valuesMandN(e.g.,"1+1"would refer to the"c"in"abcd").M-Nβ The char specified at the integral index that is the difference of integer valuesMandN(e.g.,"2-1"would refer to the"b"in"abcd").
In the specifications above, the integer valueMcontains no trailing whitespace and the integer valueNcontains no leading whitespace. Keep it tight, no stray spaces. π§
π EXAMPLE π
Test if the string in the variable string is a proper non-empty prefix of the string foobar.
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
And that's a wrap on the whole page, bestie! π This one's straight out of Tcl 8.1 and it signs itself off as string(3tcl) β go forth and manipulate some strings, you absolute icon. ππ
π¦ where this page comes from
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- 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