天天看點

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。

繼續閱讀