Write a script to replace the character ‘e’ with ‘E’ in the string ‘Weekly Challenge’. Also print the number of times the character ‘e’ is found in the string.
#!/usr/bin/env tclsh
set times [regsub -all "e" "Weekly Challenge" "E" result]
puts "Find e $times times"
puts "Output: $result"
使用 Regular Expressions 來做替代字串的任務。
也可以使用 string map 來替代字串,下面是 Replace e with E 的其它寫法:
#!/usr/bin/env tclsh
set str "Weekly Challenge"
set count 0
foreach x [split $str {}] {
if {$x == "e"} {
incr count
}
}
puts "Find e $count times"
set result [string map {e E} $str]
puts "Output: $result"
也可以在計算 e 數目的時候就同時建構字串:
#!/usr/bin/env tclsh
set str "Weekly Challenge"
set count 0
set result {}
foreach x [split $str {}] {
if {$x == "e"} {
incr count
append result "E"
} else {
append result $x
}
}
puts "Find e $count times"
puts "Output: $result"
沒有留言:
張貼留言