如何在 Tcl 中搜索文本中的子文本?
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
, and for this particular case, 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
我是 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
, and for this particular case, 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