[英]How to search for subtext in text in Tcl?
我是tcl的新手,我有一个列表1-adam 2-john 3-mark
,我必须输入要更改列表中的序列的用户,并使其列出1-adam 2-john 3-jane
用户何时要更改序列号3?
我正在尝试这个:
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'
}
您有一个好的开始。 要更换列表中的某个元素,通常可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.