Tcl version of ucfirst

Posted by Jason Noble on 08/13/2008 in perl, tcl, ucfirst |

The load balancers we use at work have a TCL command line interface. A co-worker needed a TCL function written that would take a string as input and return the string transformed so that the first letter was upper case and the rest were lower case. There is a built in string function called toupper but that capitalizes the full string instead of only the first.

My solution (shown below) is to split the string into two strings, toupper the first string and tolower the second, then append them together. The result is the equivalent of Perl’s ucfirst implemented in TCL.

[text]
proc ucfirst str {
set a [ string toupper [ string range $str 0 0 ]]
append a [ string tolower [ string range $str 1 end ]]
return $a
}
[/text]

You can use this from the command line by using tclsh. Below is what running this code will look like (the % is the tclsh prompt).

[text]
[jasonn@jnoble-vm ~]$ tclsh
% proc ucfirst str {
set a [ string toupper [ string range $str 0 0 ]]
append a [ string tolower [ string range $str 1 end ]]
return $a
}
%
% set mystring "firetruck"
firetruck
% set t [ ucfirst $mystring ]
Firetruck
% set mystring "cop car"
cop car
% set t [ ucfirst $mystring ]
Cop car
% exit
[jasonn@jnoble-vm ~]$
[/text]

Copyright © 2008-2024 Jason Noble's Technical Adventures All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.