Version 3 of string length

Updated 2003-10-17 12:03:31

Subcommand of string, returns the length of its argument in (Unicode) characters, which may differ from the result of string bytelength on the same string (because of the UTF-8 implementation).

If you want to use a name familiar from C, you might do this:

 interp alias {} strlen {} string length

2003-10-17 in the Tcl chatroom, some of us played around with silly pure-Tcl implementations of string length:

 proc strlen s {
    set n 0
    foreach char [split $s ""] {incr n}
    set n
 } ;# RS

 proc strlen s {llength [split $s ""]} ;# AM

 proc strlen string {
    regsub {.} $string +1 string
    expr 0$string
 } ;# MS

''jcw - does the above perhaps need a -all? Also, why not simply:

   return [regexp -all . $string]

 proc strlen string {expr 0[regsub -all . $string +1]} ;# dkf

The functional way:

 proc strlen {s} {
   expr {[regexp {.(.*)} $s - s] ? (1+[strlen $s]) : 0}
 } ;# EB

Category Command | Arts and crafts of Tcl-Tk programming