String case
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Take the string "alphaBETA", and demonstrate how to convert it to UPPER-CASE and lower-case. Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.
4D
<lang 4d>$string:="alphaBETA" $uppercase:=Uppercase($string) $lowercase:=Lowercase($string)</lang>
ActionScript
<lang actionscript>var string:String = 'alphaBETA'; var upper:String = string.toUpperCase(); var lower:String = string.toLowerCase();</lang>
Ada
<lang ada>with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Text_Io; use Ada.Text_Io;
procedure Upper_Case_String is
S : String := "alphaBETA";
begin
Put_Line(To_Upper(S)); Put_Line(To_Lower(S));
end Upper_Case_String;</lang>
ALGOL 68
<lang algol68># Demonstrate toupper and tolower for standard ALGOL 68 strings. This does not work for multibyte character sets. #
PROC to upper = ( CHAR c )CHAR: (
IF ABS "a" <= ABS c & ABS c <= ABS "z" THEN REPR ( ABS c - ABS "a" + ABS "A" ) ELSE c FI
);
PROC to lower = ( CHAR c )CHAR: (
IF ABS "A" <= ABS c & ABS c <= ABS "Z" THEN REPR ( ABS c - ABS "A" + ABS "a" ) ELSE c FI
);
- upper-cases s in place #
PROC str to upper = (REF STRING s)VOID : (
FOR i FROM LWB s TO UPB s DO s[i] := toupper(s[i]) OD
);
- lower-cases s in place #
PROC str to lower = (REF STRING s)VOID : (
FOR i FROM LWB s TO UPB s DO s[i] := tolower(s[i]) OD
);
main: (
STRING t := "alphaBETA"; str to upper(t); printf(($"uppercase: "gl$, t)); str to lower(t); printf(($"lowercase: "gl$, t))
)</lang>
APL
a←'abcdefghijklmnopqrstuvwxyz' A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ' X←'alphaBETA' (a,⎕AV)[(A,⎕AV)⍳'alphaBETA'] alphabeta (A,⎕AV)[(a,⎕AV)⍳'alphaBETA'] ALPHABETA
AutoHotkey
<lang autohotkey>a := "alphaBETA" StringLower, b, a ; alphabeta StringUpper, c, a ; ALPHABETA
StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"</lang>
AWK
<lang awk>BEGIN {
a = "alphaBETA"; print toupper(a), tolower(a)
}</lang>
BASIC
<lang qbasic>s$ = "alphaBETA" PRINT UCASE$(s$) PRINT LCASE$(s$)</lang>
BBC BASIC
<lang bbcbasic> INSTALL @lib$+"STRINGLIB"
original$ = "alphaBETA" PRINT "Original: " original$ PRINT "Lower case: " FN_lower(original$) PRINT "Upper case: " FN_upper(original$) PRINT "Title case: " FN_title(original$)</lang>
Output:
Original: alphaBETA Lower case: alphabeta Upper case: ALPHABETA Title case: AlphaBETA
C
The tolower and toupper functions are locale-aware. <lang c>/* Demonstrate toupper and tolower for
standard C strings. This does not work for multibyte character sets. */
- include <ctype.h>
- include <stdio.h>
/* upper-cases s in place */ void str_toupper(char *s) {
while(*s) { *s=toupper(*s); s++; }
}
/* lower-cases s in place */
void str_tolower(char *s)
{
while(*s) { *s=tolower(*s); s++; }
}
int main(int argc, char *argv[]) {
char t[255]="alphaBETA"; str_toupper(t); printf("uppercase: %s\n", t); str_tolower(t); printf("lowercase: %s\n", t); return 0;
}</lang>
C#
<lang csharp>string array = "alphaBETA"; System.Console.WriteLine(array.ToUpper()); System.Console.WriteLine(array.ToLower());</lang>
Title case is a little different: <lang csharp>System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));</lang>
C++
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.
<lang cpp>#include <algorithm>
- include <string>
- include <cctype>
/// \brief in-place convert string to upper case /// \return ref to transformed string void str_toupper(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::toupper);
}
/// \brief in-place convert string to lower case /// \return ref to transformed string void str_tolower(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::tolower);
}</lang>
Here is sample usage code:
<lang cpp>#include <iostream>
- include <string>
using namespace std; int main() {
string foo("_upperCas3Me!!"); str_toupper(foo); cout << foo << endl; str_tolower(foo); cout << foo << endl; return 0;
}</lang>
Clojure
<lang lisp>(def string "alphaBETA") (println (.toUpperCase string)) (println (.toLowerCase string))</lang>
ColdFusion
converting a string literal <lang coldfusion><cfset upper = UCase("alphaBETA")> <cfset lower = LCase("alphaBETA")></lang>
converting the value of a variable <lang coldfusion><cfset string = "alphaBETA"> <cfset upper = UCase(string)> <cfset lower = LCase(string)></lang>
Common Lisp
You can use the string-upcase function to perform upper casing:
<lang lisp>CL-USER> (string-upcase "alphaBETA") "ALPHABETA"</lang>
and you can do lower casing by using string-downcase:
<lang lisp>CL-USER> (string-downcase "alphaBETA") "alphabeta"</lang>
D
<lang d>import std.stdio, std.string;
void main() {
auto s = "alphaBETA"; writeln(s.toupper()); writeln(s.tolower());
}</lang> Output:
ALPHABETA alphabeta
Delphi
<lang pascal>writeln(uppercase('alphaBETA')); writeln(lowercase('alphaBETA'));</lang>
DWScript
<lang delphi>PrintLn(UpperCase('alphaBETA')); PrintLn(LowerCase('alphaBETA'));</lang>
E
<lang e>["alphaBETA".toUpperCase(), "alphaBETA".toLowerCase()]</lang>
Erlang
<lang erlang>string:to_upper("alphaBETA"). string:to_lower("alphaBETA").</lang>
F#
<lang fsharp> let s = "alphaBETA" let upper = s.ToUpper() let lower = s.ToLower() </lang>
Factor
<lang factor>"alphaBETA" >lower ! "alphabeta" "alphaBETA" >upper ! "ALPHABETA" "alphaBETA" >title ! "Alphabeta" "ß" >case-fold ! "ss"</lang>
Fantom
<lang fantom> fansh> a := "alphaBETA" alphaBETA fansh> a.upper // convert whole string to upper case ALPHABETA fansh> a.lower // convert whole string to lower case alphabeta fansh> a.capitalize // make sure first letter is capital AlphaBETA fansh> "BETAalpha".decapitalize // make sure first letter is not capital bETAalpha </lang>
Forth
ANS Forth does not have words to convert case for either strings or characters. For known alpha-numeric ASCII characters, the following can be used:
: tolower ( C -- c ) 32 or ; : toupper ( c -- C ) 32 invert and ; : lower ( addr len -- ) over + swap do i c@ tolower i c! loop ; : upper ( addr len -- ) over + swap do i c@ toupper i c! loop ;
If the character range is unknown, these definitions are better:
: tolower ( C -- c ) dup [char] A [char] Z 1+ within if 32 + then ; : toupper ( c -- C ) dup [char] a [char] z 1+ within if 32 - then ;
create s ," alphaBETA" s count type s count 2dup upper type s count 2dup lower type
Output:
alphaBETA ALPHABETA alphabeta
Fortran
<lang fortran> program example
implicit none character(9) :: teststring = "alphaBETA" call To_upper(teststring) write(*,*) teststring call To_lower(teststring) write(*,*) teststring contains subroutine To_upper(str) character(*), intent(in out) :: str integer :: i do i = 1, len(str) select case(str(i:i)) case("a":"z") str(i:i) = achar(iachar(str(i:i))-32) end select end do end subroutine To_upper subroutine To_lower(str) character(*), intent(in out) :: str integer :: i do i = 1, len(str) select case(str(i:i)) case("A":"Z") str(i:i) = achar(iachar(str(i:i))+32) end select end do end subroutine To_Lower
end program example</lang>
GML
<lang GML>#define cases {
x = 'alphaBETA'; y = string_upper(x); // returns ALPHABETA z = string_lower(x); // returns alphabeta show_message(y); show_message(z);
}</lang>
Go
<lang go>s := "alphaBETA" fmt.Println(strings.ToUpper(s)) // => "ALPHABETA" fmt.Println(strings.ToLower(s)) // => "alphabeta"</lang>
Groovy
<lang groovy>def str = 'alphaBETA'
println str.toUpperCase() println str.toLowerCase()</lang>
Output:
ALPHABETA alphabeta
Haskell
<lang haskell>import Data.Char
s = "alphaBETA"
lower = map toLower s upper = map toUpper s</lang>
HicEst
<lang hicest>CHARACTER str = "alphaBETA" EDIT(Text=str, UpperCase=LEN(str)) EDIT(Text=str, LowerCase=LEN(str)) EDIT(Text=str, UpperCase=1) </lang>
Icon and Unicon
<lang Icon>procedure main()
write(map("alphaBETA")) write(map("alphaBETA",&lcase,&ucase))
end</lang>
IDL
str = "alphaBETA" print, str print, strupcase(str) print, strlowcase(str)
J
Use standard utilities: <lang j> toupper 'alphaBETA' ALPHABETA
tolower 'alphaBETA'
alphabeta</lang>
or alternative definitions: <lang j>upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.) lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)</lang>
For example: <lang j> upper 'alphaBETA' ALPHABETA
lower 'alphaBETA'
alphabeta</lang>
Java
<lang java>String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase());</lang>
You could also easily create a swapCase method using Character.isLowerCase(), Character.isUpperCase(), and Character.isLetter().
JavaScript
<lang javascript>alert( "alphaBETA".toUpperCase() ); alert( "alphaBETA".toLowerCase() );</lang>
Output:
ALPHABETA alphabeta
<lang javascript>var string = "alphaBETA"; var uppercase = string.toUpperCase(); var lowercase = string.toLowerCase();</lang>
Liberty BASIC
<lang lb>input$ ="alphaBETA"
print input$ print upper$( input$) print lower$( input$)
end</lang>
Logo
print uppercase "alphaBETA ; ALPHABETA print lowercase "alphaBETA ; alphabeta
Lua
<lang Lua>str = "alphaBETA" print( string.upper(str) ) print( string.lower(str) )</lang>
M4
<lang M4>define(`upcase', `translit(`$*', `a-z', `A-Z')') define(`downcase', `translit(`$*', `A-Z', `a-z')')
define(`x',`alphaBETA') upcase(x) downcase(x)</lang>
Mathematica
<lang Mathematica>str="alphaBETA"; ToUpperCase[str] ToLowerCase[str]</lang> gives:
ALPHABETA alphabeta
MATLAB
<lang MATLAB>>> upper('alphaBETA')
ans =
ALPHABETA
>> lower('alphaBETA')
ans =
alphabeta</lang>
MAXScript
Requires MAX 2008 <lang maxscript>str = "alphaBETA" print (toUpper str) print (toLower str)</lang>
Metafont
We need to implement it, since it is not already given; the following code works only for ASCII or ASCII based encodings. (It could work anyway also for single byte encodings where letters are contiguous).
<lang metafont>vardef isbetween(expr a, i, f) =
if string a: if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)): true else: false fi else: false fi enddef;
vardef toupper(expr s) =
save ?; string ?; ? := ""; d := ASCII"A" - ASCII"a"; for i = 0 upto length(s)-1: if isbetween(substring(i, i+1) of s, "a", "z"): ? := ? & char(ASCII(substring(i,i+1) of s) + d) else: ? := ? & substring(i, i+1) of s fi; endfor ?
enddef;
vardef tolower(expr s) =
save ?; string ?; ? := ""; d := ASCII"a" - ASCII"A"; for i = 0 upto length(s)-1: if isbetween(substring(i, i+1) of s, "A", "Z"): ? := ? & char(ASCII(substring(i,i+1) of s) + d) else: ? := ? & substring(i, i+1) of s fi; endfor ?
enddef;</lang>
<lang metafont>message toupper("alphaBETA"); message tolower("alphaBETA");
end</lang>
Modula-3
<lang modula3>MODULE TextCase EXPORTS Main;
IMPORT IO, Text, ASCII;
PROCEDURE Upper(txt: TEXT): TEXT =
VAR len := Text.Length(txt); res := ""; BEGIN FOR i := 0 TO len - 1 DO res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)])); END; RETURN res; END Upper;
PROCEDURE Lower(txt: TEXT): TEXT =
VAR len := Text.Length(txt); res := ""; BEGIN FOR i := 0 TO len - 1 DO res := Text.Cat(res, Text.FromChar(ASCII.Lower[Text.GetChar(txt, i)])); END; RETURN res; END Lower;
BEGIN
IO.Put(Upper("alphaBETA\n")); IO.Put(Lower("alphaBETA\n"));
END TextCase.</lang> Output:
ALPHABETA alphabeta
MUMPS
<lang MUMPS> STRCASE(S)
SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ" SET LO="abcdefghijklmnopqrstuvwxyz" WRITE !,"Given: "_S WRITE !,"Upper: "_$TRANSLATE(S,LO,UP) WRITE !,"Lower: "_$TRANSLATE(S,UP,LO) QUIT
</lang>
Output:
USER>DO STRCASE^ROSETTA("alphaBETA") Given: alphaBETA Upper: ALPHABETA Lower: alphabeta
Nemerle
<lang Nemerle>using System.Console; using System.Globalization;
module StringCase {
Main() : void { def alpha = "alphaBETA"; WriteLine(alpha.ToUpper()); WriteLine(alpha.ToLower()); WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
}
}</lang>
NewLISP
<lang NewLISP> (upper-case "alphaBETA") (lower-case "alphaBETA") </lang>
Nial
<lang nial>toupper 'alphaBETA' =ALPHABETA tolower 'alphaBETA' =alphabeta</lang>
Objeck
<lang objeck> string := "alphaBETA"; string->ToUpper()->PrintLine(); string->ToLower()->PrintLine(); </lang>
Objective-C
<lang objc>NSLog(@"%@", [@"alphaBETA" uppercaseString]); NSLog(@"%@", [@"alphaBETA" lowercaseString]);
NSLog(@"%@", [@"foO BAr" capitalizedString]); // "Foo Bar"</lang>
OCaml
<lang ocaml>let () =
let str = "alphaBETA" in print_endline (String.uppercase str); (* ALPHABETA *) print_endline (String.lowercase str); (* alphabeta *)
print_endline (String.capitalize str); (* AlphaBETA *)
- </lang>
Octave
<lang octave>s = "alphaBETA"; slc = tolower(s); suc = toupper(s); disp(slc); disp(suc);</lang>
OpenEdge/Progress
<lang Progress (OpenEdge ABL)>caps("alphaBETA") lc("alphaBETA") </lang>
Oz
Convert to upper/lower-case: <lang oz>declare
Str = "alphaBETA"
in
{System.showInfo {Map Str Char.toUpper}} {System.showInfo {Map Str Char.toLower}}</lang>
Capitalize: <lang oz>declare
[StringX] = {Link ['x-oz://system/String.ozf']}
in
{System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"</lang>
Perl
<lang perl>my $string = "alphaBETA"; print uc($string), "\n"; # => "ALPHABETA" print lc($string), "\n"; # => "alphabeta" $string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta
print ucfirst($string), "\n"; # => "AlphaBETA" print lcfirst("FOObar"), "\n"; # => "fOObar"</lang>
Also works in Perl 4 if the my is removed.
<lang perl>my $string = "alphaBETA"; say $string.uc say $string.lc</lang>
Perl 6
<lang Perl 6>my $word = "alphaBETA" ; say $word.uc ; #uppercase say $word.lc ; #lowercase say $word.ucfirst ; #first letter uppercase say $word.lcfirst ; #first letter lowercase say $word.capitalize ; #first letter uppercase, rest lowercase </lang> Output:
ALPHABETA alphabeta AlphaBETA alphaBETA Alphabeta
PHP
<lang php>$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz</lang>
PicoLisp
<lang PicoLisp>(let Str "alphaBETA"
(prinl (uppc Str)) (prinl (lowc Str)) )</lang>
PL/I
<lang PL/I> declare s character (20) varying initial ('alphaBETA');
put skip list (uppercase(s)); put skip list (lowercase(s)); </lang>
<lang PL/I> /* An alternative to the above, which might be used if some */ /* non-standard conversion is required, is shown for */ /* converting to upper case: */ put skip list ( translate(s, 'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') );
</lang>
PL/SQL
<lang plsql>declare
vc VARCHAR2(40) := 'alphaBETA'; ivc VARCHAR2(40); lvc VARCHAR2(40); uvc VARCHAR2(40);
begin
ivc := INITCAP(vc); -- 'Alphabeta' lvc := LOWER(vc); -- 'alphabeta' uvc := UPPER(vc); -- 'ALPHABETA'
end; </lang>
Pop11
<lang pop11>lvars str = 'alphaBETA'; lowertoupper(str) => uppertolower(str) =></lang>
Powerbuilder
<lang powerbuilder>string ls_string ls_string = 'alphaBETA' ls_string = Upper(ls_string) ls_string = Lower(ls_string)</lang>
PowerShell
<lang powershell>$string = 'alphaBETA' $lower = $string.ToLower() $upper = $string.ToUpper()</lang>
Protium
Iterating through the peerset <lang html><@ ENU$$$LSTPSTLITLIT>UPP| [<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@> <@ SAY&&&LIT>alphaBETA</@>
</@></lang>
Same code in padded-out, variable-length English dialect <lang html><# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP| [<# SAY ELEMENT LIST>...</#>] <# SAY HELP ELEMENT LIST>...</#><# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|...</#> <# SAY SUPERMACRO LITERAL>alphaBETA</#>
</#></lang>
Output.
[FLC] 410400001 Flip case (410400001) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] ALPHAbeta [LOW] 410400002 Lower case (410400002) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] alphabeta [PRP] 410400003 Proper Case (410400003) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] Alphabeta [SNT] 410400004 Sentence case (410400004) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] Alphabeta [UPP] 410400005 Upper case (410400005) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] ALPHABETA
PureBasic
<lang PureBasic>s$ = "alphaBETA" upper$ = UCase(s$) ;uppercase lower$ = LCase(s$) ;lowercase</lang>
Python
<lang python>s = "alphaBETA" print s.upper() # => "ALPHABETA" print s.lower() # => "alphabeta"
print s.swapcase() # => "ALPHAbeta"
print "fOo bAR".capitalize() # => "Foo bar" print "fOo bAR".title() # => "Foo Bar"
import string print string.capwords("fOo bAR") # => "Foo Bar"</lang>
string.capwords() allows the user to define word separators, and by default behaves slightly differently than title().
<lang python>print "foo's bar".title() # => "Foo'S Bar" print string.capwords("foo's bar") # => "Foo's Bar"</lang>
R
<lang R> str <- "alphaBETA"
toupper(str) tolower(str)</lang>
Raven
<lang raven>'alphaBETA' upper 'alhpaBETA' lower</lang>
REBOL
<lang REBOL>print ["Original: " original: "alphaBETA"] print ["Uppercase:" uppercase original] print ["Lowercase:" lowercase original]</lang>
Output:
Original: alphaBETA Uppercase: ALPHABETA Lowercase: alphabeta
Retro
<lang Retro>with strings' "alphaBETA" toUpper puts "alphaBETA" toLower puts</lang>
REXX
The following code will execute correctly in ASCII and EBCDIC.
<lang rexx> x='alphaBETA' /*define the REXX variable X to a string. */
y=translate(x) /*uppercases x, stores it in Y (version 1).*/
parse upper var x y /*uppercases x, stores it in Y (version 2).*/
y=x; upper y /*store X in Y, uppercases Y (version 3).*/
y=upper(y) /*uppercases x, stores it in Y (version 4).*/
/*Some REXXes don't support the UPPER bif.*/
abc ='abcdefghijklmnopqrstuvwxyz' /*all lowercase letters.*/
abcu=abc; upper abcu /*all uppercase letters.*/
z=translate(x,abc,abcu) /*lowercases x, stores it in Z (version 1).*/
parse lower var x y /*lowercases x, stores it in Z (version 2).*/
/*Some REXXes don't support LOWER option. */
y=lower(y) /*lowercases x, stores it in Z (version 3).*/
/*Some REXXes don't support the LOWER bif.*/
</lang>
Ruby
<lang ruby>"alphaBETA".downcase # => "alphabeta" "alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".swapcase # => "ALPHAbeta" "alphaBETA".capitalize # => "Alphabeta"</lang>
Scala
<lang Scala>val s="alphaBETA" println(s.toUpperCase) //-> ALPHABETA println(s.toLowerCase) //-> alphabeta println(s.capitalize) //-> AlphaBETA println(s.reverse) //-> ATEBahpla</lang>
Scheme
<lang scheme>(define s "alphaBETA") (list->string (map char-upcase (string->list s))) (list->string (map char-downcase (string->list s)))</lang>
Using SRFI-13:
<lang scheme> > (define s "alphaBETA gammaDELTA") > (string-upcase s) ;; turn all into upper case "ALPHABETA GAMMADELTA" > (string-downcase s) ;; turn all into lower case "alphabeta gammadelta" > (string-titlecase s) ;; capitalise start of each word "Alphabeta Gammadelta" </lang>
Seed7
writeln(upper("alphaBETA")); writeln(lower("alphaBETA"));
Slate
<lang slate>'alphaBETA' toLowercase.
'alphaBETA' toUppercase.</lang>
Smalltalk
<lang smalltalk>'ALPHAbeta' asUppercase. 'ALPHAbeta' asLowercase.</lang>
SNOBOL4
There are no standard Snobol libraries or case conversion built-ins. But case functions are easy to roll using the character class keywords. Native charset only.
<lang SNOBOL4> define('uc(str)') :(uc_end) uc uc = replace(str,&lcase,&ucase) :(return) uc_end
define('lc(str)') :(lc_end)
lc lc = replace(str,&ucase,&lcase) :(return) lc_end
define('ucfirst(str)ch') :(ucfirst_end)
ucfirst str len(1) . ch = uc(ch)
ucfirst = str :(return)
ucfirst_end
define('swapc(str)') :(swapc_end)
swapc str = replace(str,&ucase &lcase, &lcase &ucase)
swapc = str :(return)
swapc_end
- # Test and display
str = 'alphaBETA' output = str output = lc(str) output = uc(str) output = ucfirst(str) output = swapc(str)
end</lang>
Output:
alphaBETA alphabeta ALPHABETA AlphaBETA ALPHAbeta
SQL
<lang sql>declare @s varchar(10) set @s = 'alphaBETA' print upper(@s) print lower(@s)</lang>
Standard ML
<lang sml>val strupr = String.map Char.toUpper; val strlwr = String.map Char.toLower;</lang>
Test
- strupr "alphaBETA"; val it = "ALPHABETA" : string - strlwr "alphaBETA"; val it = "alphabeta" : string
Tcl
<lang tcl>set string alphaBETA
- three built-in case conversion commands
string toupper $string ;# ==> ALPHABETA string tolower $string ;# ==> alphabeta string totitle $string ;# ==> Alphabeta
- not built-in
proc swapcase {s} {
foreach char [split $s ""] { if {$char eq [set CHAR [string toupper $char]]} { append new [string tolower $char] } else { append new $CHAR } } return $new
} swapcase $string ;# ==> ALPHAbeta
- better performance, but English alphabet only
proc swapcase_en {s} {
string map { a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z } $s
}
swapcase Père ;# ==> pÈRE swapcase_en Père ;# ==> pèRE</lang>
Toka
needs ctype [ i 1 - ] is i [ string.getLength 0 [ dup i + c@ toupper over i + c! ] countedLoop ] is string.toUpper [ string.getLength 0 [ dup i + c@ tolower over i + c! ] countedLoop ] is string.toLower " alphaBETA" string.toUpper type cr " alphaBETA" string.toLower type cr
UNIX Shell
<lang bash>s="alphaBETA" echo ${s^^} echo ${s,,} echo ${s^}</lang> Output:
ALPHABETA alphabeta AlphaBETA
UnixPipes
echo "alphaBETA" |tr '[a-z]' '[A-Z]' echo "alphaBETA" |tr '[A-Z]' '[a-z]'
Ursala
Case conversion functions aren't built in but can be defined using the reification operator (-:) to construct a function from a list of pairs. <lang Ursala>#import std
to_upper = * -:~& ~=`A-~p letters to_lower = * -:~& ~=`A-~rlp letters
- show+
examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'></lang> output:
ALPHABETA alphabeta
VBScript
<lang vbscript>Dim MyWord MyWord = UCase("alphaBETA") ' Returns "ALPHABETA" MyWord = LCase("alphaBETA") ' Returns "alphabeta"</lang>
Vedit macro language
<lang vedit>#1 = CP IT("alphaBETA") Case_Upper_Block(#1, CP) Case_Lower_Block(#1, CP)</lang>
Visual Basic .NET
<lang vbnet>' Define 's' Dim s AS String = "alphaBETA"
' Change 's' to Upper Case. s = s.ToUpper()
' Change 's' to Lower Case. s = s.ToLower()</lang>
- Programming Tasks
- String manipulation
- 4D
- ActionScript
- Ada
- ALGOL 68
- APL
- AutoHotkey
- AWK
- BASIC
- BBC BASIC
- C
- C sharp
- C++
- STL
- Clojure
- ColdFusion
- Common Lisp
- D
- Delphi
- Object Pascal
- Pascal
- DWScript
- E
- Erlang
- F Sharp
- Factor
- Fantom
- Forth
- Fortran
- GML
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Lua
- M4
- Mathematica
- MATLAB
- MAXScript
- Metafont
- Modula-3
- MUMPS
- Nemerle
- NewLISP
- Nial
- Objeck
- Objective-C
- OCaml
- Octave
- OpenEdge/Progress
- Oz
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- PL/SQL
- Pop11
- Powerbuilder
- PowerShell
- Protium
- PureBasic
- Python
- R
- Raven
- REBOL
- Retro
- REXX
- Ruby
- Scala
- Scheme
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- SQL
- Standard ML
- Tcl
- Toka
- UNIX Shell
- UnixPipes
- Ursala
- VBScript
- Vedit macro language
- Visual Basic .NET
- PARI/GP/Omit