簡體   English   中英

如何在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 ,並為這種特殊情況下, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM