简体   繁体   中英

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'
}

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. Both functions need the index of the element to be replaced, and because of this, I would recommend using for loop instead of 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 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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