faskiat
faskiat

Reputation: 689

Properly manipulating strings in TCL

Seems like a basic task, but I want to take a string that ends in something and replace the last 3 letters with something else. Here's my attempt:

set v "this is bob"
set index2 [string length $v]
set index1 [expr $index2 - 3]
set result [string replace $v index1 index2 dog]
puts $result; # I want it to now say "this is dog"

EDIT: Forgot to mention, the error message it gives me is:

bad index "index1": must be integer?[+-]integer? or end?[+-]integer?
    while executing
"string replace $v index1 index2 .hdr"
    invoked from within
"set result [string replace $v index1 index2 .hdr]"
    (file "string_manipulation.tcl" line 7)

Upvotes: 1

Views: 750

Answers (2)

Hai Vu
Hai Vu

Reputation: 40688

Here is one way to do it. Tcl recognizes tokens such as end, end-1, end-2, ... What you want is to replace from end-2 to end:

set v "this is bob"
set result [string replace $v end-2 end "dog"]
# Result now is "this is dog"

Update

If all you want to do is replacing the file extension, then use file rootname to remove the extension, then add your own:

set v filename.arm
set result [file rootname $v].hdr; # Replaces .arm with .hdr

This solution has the advantage of working with extensions of various lengths, not just 3.

Upvotes: 3

Nathan Stocks
Nathan Stocks

Reputation: 2164

Easy, you forgot you were in TCL right near the end. Instead of passing in the values of index1 and index2, you passed in the literal strings "index1" and "index2". So just add the missing dollar signs:

set result [string replace $v $index1 $index2 dog]

Voila! :-)

Upvotes: 3

Related Questions