首页 > 解决方案 > How to search for subtext in text in Tcl?

问题描述

I'm new to tcl, I have a list 1-adam 2-john 3-mark and I have to take input for user of which serial I have to change in list and make it list 1-adam 2-john 3-jane when user want to change serial 3?

I was trying this:

set names [split "1-adam 2-john 3-mark" " "]
puts "Enter the serial no:" 
set serial [gets stdin]
set needle $serial\-
foreach name $names {
    #here I'm trying to find  and overwrite'
}

标签: listtcl

解决方案


你有一个好的开始。要替换列表中的元素,您通常可以使用lreplace, 并且对于这种特殊情况lset也是如此。这两个函数都需要替换元素的索引,因此,我建议使用for循环而不是foreach

set names [split "1-adam 2-john 3-mark" " "]
puts "Enter the serial no:"
set serial [gets stdin]
puts "Enter new name:"     ;# Might want to add something like this for the new name
set new_name [gets stdin]
set needle $serial-        ;# You do not really need to escape the dash
for {set i 0} {$i < [llength $names]} {incr i} {
    set name [lindex $names $i]
    if {[string match $needle* $name]} {
        set names [lreplace $names $i $i $needle$new_name]
    }
}
puts $names
# 1-adam 2-john 3-jane

使用lset将是:

lset names $i $needle$new_name

另一种方法是使用 查找需要更改的元素的索引lsearch,在这种情况下,您不需要循环:

set names [split "1-adam 2-john 3-mark" " "]
puts "Enter the serial no:"
set serial [gets stdin]
puts "Enter new name:"
set new_name [gets stdin]
set needle $serial-

set index [lsearch $names $needle*]
if {$index > -1} {
    lset names $index $needle$new_name
} else {
    puts "No such serial in the list!"
}

puts $names
# 1-adam 2-john 3-jane

推荐阅读