tcl/tk實例詳解——string(二)

    這裏對string命令中的幾個子命令使用實例進行一些解釋,以便於更加容易理解string命令中的各個子命令,本文僅對以下幾個string命令進行實例解析。分別是repeat、replace、reverse、tolower、totitle、toupper、trim、trimleft、trimright、wordend和wordstart幾個子命令。
 
    string repeat string count
    非常簡單,返回一個把string重複count次的字符串。
    % string repeat "This" 3
    ThisThisThis
 
    string replace string first last ?newstring?
    也很簡單,使用newstring替換string中的first到last的字符串,如果沒有newstring,就是使用空代替。
    % string replace "This is a tcltk example" 10 14 TCLTK
    This is a TCLTK example
    如果沒有newstring:
    % string replace "This is a tcltk example" 10 14
    This is a  example
 
    string reverse string
    返回string的反序字符串:
    % string reverse "This is a tcltk example"
    elpmaxe ktlct a si sihT
 
    string tolower string ?first? ?last?
    string totitle string ?first? ?last?
    string toupper string ?first? ?last?
    這三個命令放在一起,是因爲三個命令的格式完全相同,只是實現了不同的操作。
    將一個字符串全部變爲小寫形式:
    % string tolower "This is a tcltk example"
    this is a tcltk example
    將一個字符串全部變爲大寫形式:
    % string toupper "This is a tcltk example"
    THIS IS A TCLTK EXAMPLE
    將一個字符串裏面開頭的第一個字母轉換爲大寫形式,其他字符轉化爲小寫形式:
    % string totitle "this is a TCLTK example"
    This is a tcltk example
    first和last指定了轉換的範圍,操作與上述完全相同,只是對字符串的作用範圍不同。
 
    string trim string ?chars?
    string trimleft string ?chars?
    string trimright string ?chars?
    這三個命令實現的功能類似,都是去掉chars字符,只是操作的位置有所區別。如果沒有指定chars字符,則去掉空白符(包括空格符、製表符、換行符、回車符)。trim對字符串開頭和結尾都操作,trimleft只對字符串開頭操作,trimright只對字符串結尾操作。
    % string trim "!!This is a tcltk example!!" !
    This is a tcltk example
    % string trimleft "!!This is a tcltk example!!" !
    This is a tcltk example!!
    % string trimright "!!This is a tcltk example!!" !
    !!This is a tcltk example
 
    string wordend string charIndex
    string wordstart string charIndex
    這兩個命令類似,wordend是找出給定索引的字符所在的單詞的下一個單詞的第一個字符的索引,wordstart是找出給定索引的字符所在的單詞的第一個字符的索引。用語言描述比較難理解,下面舉例說明就非常清晰了:
    % string wordend "This is a tcltk example" 12
    15
    12索引爲tcltk中的l字符,那麼返回的結果就是l所在的詞tcltk的下一個詞example中的第一個字符e的索引,即15。
    % string wordstart "This is a tcltk example" 12
    10
    12索引爲tcltk中的l字符,那麼返回的結果就是l所在的詞的第一個字符t的索引,即10。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章