2015-02-10 47 views
-1

分割字符串如何在TCL如何在TCL

分割字符串考虑代码:

set ip "12345678910" 

我想将字符串分割成4串为一组,即1234 5678 910。 ...

回答

0
set ip "12345678910" 
set len [ string length $ip ] 
set str_start 0; #Start Index 
set str_end 3; #End Index 

for { set i 0 } { $str_start < $len } { incr i } { 
    #Appending it as 'list' 
    lappend list_result [ string range $ip $str_start $str_end ] 
    #Increasing the index values 
    incr str_start 4 
    incr str_end 4 
} 
puts $list_result 

输出

1234 5678 910 
2

如何:

regexp -all -inline {\d{1,4}} 12345678910 

这将返回一个列表具有4位数字的每个元素,除了最后能有更少...

1

我通常建议不要使用regexp,但regexp -all -inline {\d{1,4}} 12345678910作为船长的答案实际上可能是最好的解决方案。如果字符不必是数字,则regexp -all -inline {.{1,4}} 1a2b3c4d5e6将允许字符串中的任何字符。

另一种解决方案是使用lmap {a b c d} [split 12345678910 {}] {lindex $a$b$c$d}

(单参数lindex调用仅仅是恒等函数,即,结果是等于参数。)

文档:lindexlmapregexpsplit