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 using return -level 0, and it's more efficient than making a list of args and using join with an empty join string. Slay. πŸ’–
  • string compare ?-nocase? ?-length length? string1 string2 β€” Does a character-by-character comparison of string1 and string2. You get -1, 0, or 1 depending on whether string1 is lexicographically less than, equal to, or greater than string2. If -length is specified, only the first length characters get compared. If -length is negative, it's ignored. If -nocase is specified, the comparison is case-insensitive. Easy. ✨
  • string equal ?-nocase? ?-length length? string1 string2 β€” Does a character-by-character comparison of string1 and string2. Returns 1 if they're identical, or 0 if not. If -length is specified, only the first length characters get compared. If -length is negative, it's ignored. If -nocase is specified, the comparison is case-insensitive. 🫢
  • string first needleString haystackString ?startIndex? β€” Searches haystackString for a sequence of characters that exactly match needleString. If it finds one, it returns the index of the first character in the first match inside haystackString. If not found, you get -1. If startIndex is specified (in any of the forms described in STRING INDICES), the search starts with the character in haystackString specified 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 the charIndex'th character of the string argument. A charIndex of 0 is the first character. charIndex can be specified as described in STRING INDICES. If charIndex is less than 0 or greater than or equal to the length of the string, you get an empty string back. πŸŽ€
  • string insert string index insertString β€” Returns a copy of string with insertString inserted at the index'th character. The index can be specified as described in STRING INDICES. 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 β€” Returns 1 if string is a valid member of the specified character class, otherwise 0. If -strict is specified, an empty string returns 0; otherwise an empty string returns 1 on any class. If -failindex is specified, then if the function returns 0, the index in the string where the class stopped being valid gets stored in the variable named varname. The varname won't be set if the check returns 1. 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 to Tcl_GetBoolean.
    • control β€” Any Unicode control character.
    • dict β€” Any proper dict structure, with optional surrounding whitespace. In case of improper dict structure, 0 is returned and the varname will contain the index of the β€œelement” where the dict parsing fails, or -1 if 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 to Tcl_GetDoubleFromObj.
    • entier β€” Synonym for integer.
    • false β€” Any of the forms allowed to Tcl_GetBoolean where 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 routine Tcl_GetBignumFromObj.
    • list β€” Any proper list structure, with optional surrounding whitespace. In case of improper list structure, 0 is returned and the varname will contain the index of the β€œelement” where the list parsing fails, or -1 if 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 to Tcl_GetBoolean where 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, 0 is returned and the varname will 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? β€” Searches haystackString for a sequence that exactly matches needleString. If it finds one, it returns the index of the first character in the last such match inside haystackString. If there's no match, you get -1. If lastIndex is specified (in any of the forms described in STRING INDICES), only the characters in haystackString at or before that lastIndex are 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 in string. 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 in string based on the key-value pairs in mapping. mapping is a list of key value key value ... just like the form returned by array get. Every instance of a key in the string gets replaced with its corresponding value. If -nocase is 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. string is 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 if pattern matches string; return 1 if it does, 0 if it doesn't. If -nocase is 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 in pattern:
    • * β€” Matches any sequence of characters in string, including a null string.
    • ? β€” Matches any single character in string.
  • [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 -nocase it'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 πŸ’–). Index 0 = the very first character of the string; index end = 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 was end. 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 is 0, 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 ✨). Index 0 = 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 as end. 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 than 0. 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 which string is space returns 1, 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 which string is space returns 1, 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 which string is space returns 1, 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, 2 would point at the "c" in "abcd". πŸ”₯
  • end β€” the last char of the string. So end would 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

expr(n), list(n)


πŸ”‘ 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
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms