String case
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
[edit] 4D
$string:="alphaBETA"
$uppercase:=Uppercase($string)
$lowercase:=Lowercase($string)
[edit] ActionScript
var string:String = 'alphaBETA';
var upper:String = string.toUpperCase();
var lower:String = string.toLowerCase();
[edit] 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;
[edit] ALGOL 68
# 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))
)
[edit] APL
Works with: APL2
a←'abcdefghijklmnopqrstuvwxyz'
A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
X←'alphaBETA'
(a,⎕AV)[(A,⎕AV)⍳'alphaBETA']
alphabeta
(A,⎕AV)[(a,⎕AV)⍳'alphaBETA']
ALPHABETA
[edit] 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"
[edit] AWK
BEGIN {
a = "alphaBETA";
print toupper(a), tolower(a)
}
[edit] BASIC
Works with: QBasic
s$ = "alphaBETA"
PRINT UCASE$(s$)
PRINT LCASE$(s$)
[edit] C
The tolower and toupper functions are locale-aware.
/* 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;
}
[edit] C++
Works with: g++ version 3.4.4 (cygming special)
Library: STL
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.
#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);
}
Here is sample usage code:
#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;
}
[edit] C#
string array = "alphaBETA";
System.Console.WriteLine(array.ToUpper());
System.Console.WriteLine(array.ToLower());
Title case is a little different:
System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
[edit] Clojure
(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string))
[edit] ColdFusion
converting a string literal
<cfset upper = UCase("alphaBETA")>
<cfset lower = LCase("alphaBETA")>
converting the value of a variable
<cfset string = "alphaBETA">
<cfset upper = UCase(string)>
<cfset lower = LCase(string)>
[edit] Common Lisp
You can use the string-upcase function to perform upper casing:
CL-USER> (string-upcase "alphaBETA")
"ALPHABETA"
and you can do lower casing by using string-downcase:
CL-USER> (string-downcase "alphaBETA")
"alphabeta"
[edit] D
import tango.text.Unicode : toUpper, toLower;
import tango.io.Stdout;
void main() {
auto str = "alphaBETA";
Stdout(str.toUpper()).newline;
Stdout(str.toLower()).newline;
}
[edit] Delphi
writeln(uppercase('alphaBETA'));
writeln(lowercase('alphaBETA'));
[edit] E
["alphaBETA".toUpperCase(),
"alphaBETA".toLowerCase()]
[edit] Erlang
string:to_upper("alphaBETA").
string:to_lower("alphaBETA").
[edit] F#
let s = "alphaBETA"
let upper = s.ToUpper()
let lower = s.ToLower()
[edit] Factor
"alphaBETA" >lower ! "alphabeta"
"alphaBETA" >upper ! "ALPHABETA"
"alphaBETA" >title ! "Alphabeta"
"ß" >case-fold ! "ss"
[edit] 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 ;
Works with: Win32Forth version 4.2
create s ," alphaBETA" s count type s count 2dup upper type s count 2dup lower type
Output:
alphaBETA ALPHABETA alphabeta
[edit] Fortran
Works with: Fortran version 90 and later
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
[edit] Go
s := "alphaBETA"
fmt.Println(strings.ToUpper(s)) // => "ALPHABETA"
fmt.Println(strings.ToLower(s)) // => "alphabeta"
[edit] Groovy
def str = 'alphaBETA'
println str.toUpperCase()
println str.toLowerCase()
Output:
ALPHABETA alphabeta
[edit] Haskell
import Data.Char
s = "alphaBETA"
lower = map toLower s
upper = map toUpper s
[edit] HicEst
CHARACTER str = "alphaBETA"
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, UpperCase=1)
[edit] Icon and Unicon
[edit] Icon
procedure main()
write(map("alphaBETA"))
write(map("alphaBETA",&lcase,&ucase))
end
[edit] Unicon
This Icon solution works in Unicon.
[edit] IDL
str = "alphaBETA" print, str print, strupcase(str) print, strlowcase(str)
[edit] J
Use standard utilities:
toupper 'alphaBETA'
ALPHABETA
tolower 'alphaBETA'
alphabeta
or alternative definitions:
upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.)
lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)
For example:
upper 'alphaBETA'
ALPHABETA
lower 'alphaBETA'
alphabeta
[edit] Java
String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
You could also easily create a swapCase method using Character.isLowerCase(), Character.isUpperCase(), and Character.isLetter().
[edit] JavaScript
alert( "alphaBETA".toUpperCase() );
alert( "alphaBETA".toLowerCase() );
Output:
ALPHABETA alphabeta
Works with: NJS version 0.2.5
var string = "alphaBETA";
var uppercase = string.toUpperCase();
var lowercase = string.toLowerCase();
[edit] Liberty BASIC
input$ ="alphaBETA"
print input$
print upper$( input$)
print lower$( input$)
end
[edit] Logo
print uppercase "alphaBETA ; ALPHABETA print lowercase "alphaBETA ; alphabeta
[edit] M4
define(`upcase', `translit(`$*', `a-z', `A-Z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')
define(`x',`alphaBETA')
upcase(x)
downcase(x)
[edit] Mathematica
str="alphaBETA";
ToUpperCase[str]
ToLowerCase[str]
gives:
ALPHABETA alphabeta
[edit] MATLAB
>> upper('alphaBETA')
ans =
ALPHABETA
>> lower('alphaBETA')
ans =
alphabeta
[edit] MAXScript
Requires MAX 2008
str = "alphaBETA"
print (toUpper str)
print (toLower str)
[edit] 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).
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;
message toupper("alphaBETA");
message tolower("alphaBETA");
end
[edit] Modula-3
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.
Output:
ALPHABETA alphabeta
[edit] MUMPS
Output:
STRCASE(S)
SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SET LO="abcdefghijklmnopqrstuvwxyz"
WRITE !,"Given: "_S
WRITE !,"Upper: "_$TRANSLATE(S,LO,UP)
WRITE !,"Lower: "_$TRANSLATE(S,UP,LO)
QUIT
USER>DO STRCASE^ROSETTA("alphaBETA")
Given: alphaBETA
Upper: ALPHABETA
Lower: alphabeta
[edit] NewLISP
(upper-case "alphaBETA")
(lower-case "alphaBETA")
[edit] Nial
toupper 'alphaBETA'
=ALPHABETA
tolower 'alphaBETA'
=alphabeta
[edit] Objective-C
Works with: GNUstep Works with: Cocoa
NSLog(@"%@", [@"alphaBETA" uppercaseString]);
NSLog(@"%@", [@"alphaBETA" lowercaseString]);
NSLog(@"%@", [@"foO BAr" capitalizedString]); // "Foo Bar"
[edit] Objeck
string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();
[edit] OCaml
let () =
let str = "alphaBETA" in
print_endline (String.uppercase str); (* ALPHABETA *)
print_endline (String.lowercase str); (* alphabeta *)
print_endline (String.capitalize str); (* AlphaBETA *)
;;
[edit] Octave
s = "alphaBETA";
slc = tolower(s);
suc = toupper(s);
disp(slc);
disp(suc);
[edit] Oz
Convert to upper/lower-case:
declare
Str = "alphaBETA"
in
{System.showInfo {Map Str Char.toUpper}}
{System.showInfo {Map Str Char.toLower}}
Capitalize:
declare
[StringX] = {Link ['x-oz://system/String.ozf']}
in
{System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"
[edit] OpenEdge/Progress
caps("alphaBETA")
lc("alphaBETA")
[edit] Perl
Works with: Perl version 5.x
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"
Also works in Perl 4 if the my is removed.
Works with: Perl version 6
my $string = "alphaBETA";
say $string.uc
say $string.lc
[edit] 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
Output:
ALPHABETA alphabeta AlphaBETA alphaBETA Alphabeta
[edit] 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
[edit] PicoLisp
(let Str "alphaBETA"
(prinl (uppc Str))
(prinl (lowc Str)) )
[edit] PL/I
declare s character (20) varying initial ('alphaBETA');
put skip list (uppercase(s));
put skip list (lowercase(s));
/* 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') );
[edit] PL/SQL
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;
[edit] Pop11
lvars str = 'alphaBETA';
lowertoupper(str) =>
uppertolower(str) =>
[edit] Powerbuilder
string ls_string
ls_string = 'alphaBETA'
ls_string = Upper(ls_string)
ls_string = Lower(ls_string)
[edit] PowerShell
$string = 'alphaBETA'
$lower = $string.ToLower()
$upper = $string.ToUpper()
[edit] Protium
Iterating through the peerset
<@ ENU$$$LSTPSTLITLIT>UPP|
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@>
<@ SAY&&&LIT>alphaBETA</@>
</@>
Same code in padded-out, variable-length English dialect
<# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP|
[<# SAY ELEMENT LIST>...</#>] <# SAY HELP ELEMENT LIST>...</#><# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|...</#>
<# SAY SUPERMACRO LITERAL>alphaBETA</#>
</#>
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
[edit] PureBasic
s$ = "alphaBETA"
upper$ = UCase(s$) ;uppercase
lower$ = LCase(s$) ;lowercase
[edit] 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"
string.capwords() allows the user to define word separators, and by default behaves slightly differently than title().
print "foo's bar".title() # => "Foo'S Bar"
print string.capwords("foo's bar") # => "Foo's Bar"
[edit] R
str <- "alphaBETA"
toupper(str)
tolower(str)
[edit] Raven
'alphaBETA' upper
'alhpaBETA' lower
[edit] REBOL
print ["Original: " original: "alphaBETA"]
print ["Uppercase:" uppercase original]
print ["Lowercase:" lowercase original]
Output:
Original: alphaBETA Uppercase: ALPHABETA Lowercase: alphabeta
[edit] Ruby
Works with: Ruby version 1.8
"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".capitalize # => "Alphabeta"
[edit] Scala
val s="alphaBETA"
println(s.toUpperCase) //-> ALPHABETA
println(s.toLowerCase) //-> alphabeta
println(s.capitalize) //-> AlphaBETA
println(s.reverse) //-> ATEBahpla
[edit] Scheme
(define s "alphaBETA")
(list->string (map char-upcase (string->list s)))
(list->string (map char-downcase (string->list s)))
[edit] Seed7
writeln(upper("alphaBETA"));
writeln(lower("alphaBETA"));
[edit] Slate
'alphaBETA' toLowercase.
'alphaBETA' toUppercase.
[edit] Smalltalk
'ALPHAbeta' asUppercase.
'ALPHAbeta' asLowercase.
[edit] 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.
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
Output:
alphaBETA alphabeta ALPHABETA AlphaBETA ALPHAbeta
[edit] Standard ML
val strupr = String.map Char.toUpper;
val strlwr = String.map Char.toLower;
Test
- strupr "alphaBETA"; val it = "ALPHABETA" : string - strlwr "alphaBETA"; val it = "alphabeta" : string
[edit] SQL
Works with: MS SQL version 2005
DECLARE @s VARCHAR(10)
SET @s = 'alphaBETA'
print UPPER(@s)
print LOWER(@s)
[edit] 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
[edit] 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
[edit] UnixPipes
echo "alphaBETA" |tr '[a-z]' '[A-Z]' echo "alphaBETA" |tr '[A-Z]' '[a-z]'
[edit] 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.
#import std
to_upper = * -:~& ~=`A-~p letters
to_lower = * -:~& ~=`A-~rlp letters
#show+
examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'>
output:
ALPHABETA alphabeta
[edit] VBScript
Dim MyWord
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA") ' Returns "alphabeta"
[edit] Vedit macro language
#1 = CP
IT("alphaBETA")
Case_Upper_Block(#1, CP)
Case_Lower_Block(#1, CP)
[edit] Visual Basic .NET
Works with: Visual Basic version 2008
' Define 's'
Dim s AS String = "alphaBETA"
' Change 's' to Upper Case.
s = s.ToUpper()
' Change 's' to Lower Case.
s = s.ToLower()

