1. 程式人生 > >tcl/tk參考——列表操作split

tcl/tk參考——列表操作split

.

.

名稱

split - 將字串分解成Tcl列表

語法

split string ?splitChars?

描述

根據splitChars變元中的字元分解string,返回一個列表。每個列表元素由string中在splitChars字元之間的字元組成,如果string含有兩個連續的字元與splitChars中的字元相同或者第一或最後一個字元為splitChars中的字元就返回一個空列表元素,如果splitChars是一個空字串那麼string的每一個字元作為單獨的元素組成列表,預設splitChars為空格符。

示例

使用給定的字元分解一個網路使用者組名:

split "comp.lang.tcl.announce" .
       comp lang tcl announce

split命令使用splitChars所有的字元作為分解字元,例如分解字元為"ab",那麼作為分解的字元不是字串"ab",而是ab都作為分解字元,如下:

split "alpha beta gamma" "temp"
       al {ha b} {} {a ga} {} a

從一個字串中釋放列表字元:

split "Example with {unbalanced brace character"
       Example with /{unbalanced brace character

分解一個字串為單獨的字元列表:

split "Hello world" {}
       H e l l o { } w o r l d

分析一個Unix的/etc/passwd檔案,檔案內容由一行一行組成,使用換行符來分解檔案。

## Read the file
set fid [open /etc/passwd]
set content [read $fid]
close $fid
## Split into records on newlines
set records [split $content "/n"]
## Iterate over the records
foreach rec $records {
   ## Split into fields on colons
   set fields [split $rec ":"]
   ## Assign fields to variables and print some out...
   lassign $fields /
         userName password uid grp longName homeDir shell
   puts "$longName uses [file tail $shell] for a login shell"
}