Piyush
Piyush

Reputation: 5315

How can I cut the substring from a string in tcl

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.

Upvotes: 12

Views: 57794

Answers (3)

TrojanName
TrojanName

Reputation: 5355

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

Upvotes: 10

glenn jackman
glenn jackman

Reputation: 246744

If processor time isn't a problem, split it into a list and take the 2nd element:

set part1 [lindex [split $line] 1]

If the string can have an arbitrary number of words,

set new [join [lrange [split $line] 1 end]]

However, I'd use Donal's suggestion and stick with string operations.

Upvotes: 6

hzrari
hzrari

Reputation: 1933

I think, the best way to do it in Tcl, is:

set s "NYMEX UTBPI"
regexp -indices " " $s index;
puts [lindex $index 0]

the variable index will contain the first and the last index of your matching pattern. Here, as you are looking for single char, first and last will be the same, so you can use

puts [lindex $index 0]

or

puts [lindex $index 1]

For more info, this is the official doc: http://www.tcl.tk/man/tcl8.5/TclCmd/regexp.htm#M7

Upvotes: 2

Related Questions