String case
From Rosetta Code
[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: QuickBasic version 4.5
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());
[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] 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] 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=: (a.,~a.{~65+i.26) {~ (a.,~a.{~97+i.26) i. ]
lower=: (a.,~a.{~97+i.26) {~ (a.,~a.{~65+i.26) 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] 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] 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] 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] 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
declare
fun {SwapCase Ch}
if {Char.isUpper Ch} then {Char.toLower Ch}
elseif {Char.isLower Ch} then {Char.toUpper Ch}
else Ch end
end
Str = "alphaBETA"
in
{System.showInfo {Map Str Char.toLower}}
{System.showInfo {Map Str Char.toUpper}}
{System.showInfo {Map Str SwapCase}}
[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] 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] 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] PowerShell
$string = 'alphaBETA'
$lower = $string.ToLower()
$upper = $string.ToUpper()
[edit] Python
s = "alphaBETA"
print s.upper() # => "ALPHABETA"
print s.lower() # => "alphabeta"
print s.swapcase() # => "ALPHAbeta"
print s.capitalize() # => "Alphabeta"
import string
print string.capwords("fOo bAR") # => "Foo 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] 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] 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()







