Monday, December 7, 2015

strings

Strings

  • A string is a sequence of letters, it always need not be enclosed in the quotes until you use some white spaces in between the words. Tcl is a string based language it provides rich set of operations on strings.
Examples :
set str1 one
set str2 "two three"

set str3 I\ need\ not\ enclose\ this\ in\ quotes

  • Following operations can be executed on strings:
    • string compare
    • string equal
    • string length
    • string match #global expression
    • string toupper
    • string tolower
    • string totitle #it will convert the starting letter of string to uppercase
    • string index
    • string range
    • string reverse
Example :
set str1 Tcl
set str2 "Tcl programmer"
set str3 tcl
#The string compare command compares strings character by character. If it finds that the first characters of both strings are equal,
#it continues with the second character, until the end. It returns 0 if the strings are equal and -1
#if a non-matching character in the first string is located in the ASCII table before the character of the second string.
#The 1 number is returned if the non-matching character of the first string is located after the character of the second string.
puts [string compare $str1 $str2 ] ; #output is -1
puts [string compare -length 3 $str3 $str2 ] ; #output is 1
puts [string compare -length 3 $str1 $str2 ] ; #output is 0, it checks first 3 letters in the string
#string equal can be used to compare strings, it returns 1 if they are true else 0 for false. It checks for case
puts [string equal $str2 $str3 ] ; #output is 0
puts [string equal -length 3 $str2 $str3 ] ; #output is 1, it checks first 3 letters in the string
puts [string length $str1] ; #output is 3
puts [string match Tcl* $str2] ; #global expression
puts [string toupper $str1] ; #Output : TCL
puts [string tolower $str1]; #Output : tcl
#string totitle #it will convert the starting letter of string to uppercase
puts [string totitle $str3]; # Output : Tcl
#To get the last letter of the string
puts [string index $str1 end]
#to get range of letters
puts [string range $str2 2 5]; #output : l pr
puts [string reverse $str2]
#Output:remmargorp lcT
view raw strings.tcl hosted with ❤ by GitHub




No comments: