2013-08-01 92 views
1

看起來像一個基本任務,但我想要一個以某種東西結尾的字符串,並用其他東西替換最後3個字母。這裏是我的嘗試:正確操縱TCL中的字符串

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" 

編輯:忘了提,它給我的錯誤信息是:

 
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) 
+0

只是爲了好奇,你爲什麼假設最後一個單詞總是3個字母? – Varun

+0

由於我將使用文件擴展名.am,並且我想用.hdr替換它以保存爲不同的輸出。 – elefun

回答

3

這是一種方法。 TCL識別標記,如endend-1end-2,......你想要的是從end-2end取代:

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

更新

如果你想要做的是替換文件擴展名,然後使用file rootname刪除擴展,然後加上自己:

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

該解決方案具有不同長度,不舉的擴展工作的優勢st 3.

+2

+1。或者,保留除最後3個字符外的所有字符:'set result'[字符串範圍$ v 0結尾-3]狗「' –

+0

我喜歡這個,簡單得多 – elefun

3

容易,你忘了你在TCL右側接近尾聲。您不是通過的值索引1索引2,而是傳入字符串「index1」和「index2」。所以只需添加缺失的美元符號:

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

瞧! :-)

+0

現在,我不覺得愚蠢。那些該死的美元符號總是躲過我 – elefun