简体   繁体   English

如何在Tcl中的文本中搜索次文本?

[英]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? 我是tcl的新手,我有一个列表1-adam 2-john 3-mark ,我必须输入要更改列表中的序列的用户,并使其列出1-adam 2-john 3-jane用户何时要更改序列号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'
}

You have a good start. 您有一个好的开始。 To replace an element in a list, you can usually use lreplace , and for this particular case, lset as well. 要更换列表中的某个元素,通常可以使用lreplace ,并为这种特殊情况下, lset也是如此。 Both functions need the index of the element to be replaced, and because of this, I would recommend using for loop instead of foreach : 这两个函数都需要替换元素的索引,因此,我建议使用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

Using lset would be: 使用lset将是:

lset names $i $needle$new_name

Another way you could do it is to find the index of the element that you need to change using lsearch , in which case you won't need a loop: 您可以执行的另一种方法是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM