list - 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'
}
解决方案
你有一个好的开始。要替换列表中的元素,您通常可以使用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
推荐阅读
- php - 第一个关系的 Laravel 6.x 关系默认值
- jekyll - 如何解决 Jekyll-Include-Cache 问题?
- amazon-web-services - AWS s3 同步从 s3 复制到 EMR 很慢
- vb.net - VB.NET 列表视图委托
- node.js - 如何确定 NPM 包是实现 ES5 还是 ES6 模块?
- docker - dotnet restore 使用 docker Jenkins 容器失败
- jquery - 为什么这个 jquery 方法不返回 SELECTED 值?
- javascript - Node Js,多次调用导出的函数
- python-3.x - 如何在给定增长率和特殊规则的情况下获得 pandas 的累积增长?
- css - Ruby on Rails 6 -- 使用 Webpacker 和 Bootstrap 在局部视图上没有 CSS