确定数字是否包含 Tcl 中的数字

Determine if a number contains a digit in Tcl

我正在尝试编写一个接受列表的函数,对于列表中的每个数字,我希望它检查其中是否有数字 5。如果数字 5 在数字中,它将打印 true 并移动到列表中的下一个数字,直到结束

示例是列表 [155 12 14 6 254 15]

155 打印为真,因为其中有一个 5

12 打印 false 因为里面没有 5

等..

这是我目前所做的

proc containsDigit {l} {
    foreach nxt $l {

    while {$nxt!= 0} {
    set int [expr {fmod($nxt, 10)}]

    if {$int == 5 } {
        puts "true"
            }else{
                set $nxt [expr {$nxt/10}]
            }
        puts false

    }

    }
}

set a [list 155 12 14 6 254 15]
containsDigit $a

感谢您的帮助!

不使用 fmod(),而应使用整数模运算符:

设置整数 [expr {$nxt % 10}]

当找到 'true' 条件时,您需要 break 跳出循环。如果有 是 5 的礼物,你不想再看。

这里的语法错误:

 set $nxt [expr {$nxt/10}]

例如,这会将变量 12 设置为 1。 你想要:

 set nxt [expr {$nxt/10}]

最简单的方法是将数字视为字符串并使用string firststring match。我更喜欢 string match.

proc containsDigit {l} {
    foreach nxt $l {
        if {[string match *5* $nxt]} {
            puts "true"
        } else {
            puts "false"
        }
    }
}

如果数字可能是十六进制的,但您只想搜索十进制形式,请使用 format %d:

条件化要搜索的字符串
proc containsDigit {l} {
    foreach nxt $l {
        if {[string match *5* [format "%d" $nxt]]} {
            puts "true"
        } else {
            puts "false"
        }
    }
}