Welcome, guest | Sign In | My Account | Store | Cart

It returns the Xth token in a sentence.. like: i have a sentence divided by : and i want to get the second value sentence: set x "Value 1 : Value 2 : Value 3" [gettok $x 2 :] is returns <b>Value 2</b> if you use 0 as the number...it will returns the number of tokens in this case... <b>3</b>

Tcl, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
proc gettok {1 2 3} {
 if {![string match -nocase *$3* $1]&&$2==1} {return $1}
 if {![string match -nocase *$3* $1]&&$2>1} {return}
 if {$2=="0"} {
  if {[string match -nocase *$3* $1]} {
   set a [split $1 $3];return [llength $a]
  };return 1
 }
 set a [split $1 $3];if {$2>[llength $a]} {return}
 if {[lindex $a [expr $2 - 1]]==""&&[lindex $a $2]!=""} {return [lindex $a $2]}
 return [lindex $a [expr $2 - 1]]
}

2 comments

Richard Suchenwirth 20 years, 3 months ago  # | flag

A simpler alternative. Wouldn't this be simpler and more robust?

proc gettok {data field separator} {
   string trim [lindex [split $data $separator] $field]
} ;# RS
Kiko The King (author) 20 years, 3 months ago  # | flag

A simpler alternative.. simplier yes, more robust no ;] mine checks for mistakes and everything.. if u know mirc scripting..i tried to make a +- port of $gettok to tcl..doesnt do quite the same cose in mirc is more complex supports things like -3 2-4 4-..and that would make gettok bigger... and urs doesnt do the same s mine does..test the examples i gave with urs ;]

Created by Kiko The King on Tue, 18 Nov 2003 (MIT)
Tcl recipes (162)
Kiko The King's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks