How can I cut the substring from a string in tcl

tcl
Piyush picture Piyush · Apr 10, 2013 · Viewed 39.6k times · Source

I have string like NYMEX UTBPI. Here I want to fetch the index of white space in middle of NYMEX and UTBPI and then from that index to last index I want to cut the substring. In this case my substring will be UTBPI I'm using below

set part1 [substr $line [string index  $line " "] [string index  $line end-1]]

I'm getting below error.

wrong # args: should be "string index string charIndex"
    while executing
"string index  $line  "
    ("foreach" body line 2)
    invoked from within
"foreach line $pollerName {
set part1 [substr $line [string index  $line  ] [string index  $line end-1]]
puts $part1
puts $line
}"
    (file "Config.tcl" line 9)

Can you give me the idea on how can I do some other string manupulation as well. Any good link for this.

Answer

TrojanName picture TrojanName · Apr 10, 2013

I would just use string range and pass it the index of the whitespace (that you can find using string first or whatever).

% set s "NYMEX UTBPI"
NYMEX UTBPI
% string range $s 6 end
UTBPI

Or using string first to dynamically find the whitespace:

% set output [string range $s [expr {[string first " " $s] + 1}] end]
UTBPI