String case
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] 6502 Assembly
.lf case6502.lst
.cr 6502
.tf case6502.obj,ap1
;------------------------------------------------------
; String Case for the 6502 by barrym95838 2013.04.07
; Thanks to sbprojects.com for a very nice assembler!
; The target for this assembly is an Apple II with
; mixed-case output capabilities. Apple IIs like to
; work in '+128' ascii, so this version leaves bit 7
; alone, and can be used with either flavor.
; 6502s work best with data structures < 256 bytes;
; several instructions would have to be added to
; properly deal with longer strings.
; Tested and verified on AppleWin 1.20.0.0
;------------------------------------------------------
; Constant Section
;
StrPtr = $6 0-page temp pointer (2 bytes)
Low = $8 0-page temp low bound
High = $9 0-page temp high bound
CharOut = $fded Specific to the Apple II
BigA = "A" 'A' for normal ascii
BigZ = "Z" 'Z' " " "
LittleA = "a" 'a' " " "
LittleZ = "z" 'z' " " "
;======================================================
.or $0f00
;------------------------------------------------------
; The main program
;
main ldx #sTest Point to the test string
lda /sTest
jsr puts print it to stdout
jsr toUpper convert to UPPER-case
jsr puts print it
jsr toLower convert to lower-case
jmp puts print it and return to caller
;------------------------------------------------------
toUpper ldy #LittleA
sty Low set up the flip range
ldy #LittleZ
bne toLow2 return via toLower's tail
;------------------------------------------------------
toLower ldy #BigA
sty Low set up the flip range
ldy #BigZ
toLow2 sty High
; return via fall-thru to flip
;------------------------------------------------------
; Given a NUL-terminated string at A:X, flip the case
; of any chars in the range [Low..High], inclusive;
; only works on the first 256 bytes of a long string
; Uses: StrPtr, Low, High
; Preserves: A, X
; Trashes: Y
;
flip stx StrPtr init string pointer
sta StrPtr+1
ldy #0
pha save A
flip2 lda (StrPtr),y get string char
beq flip5 done if NUL
cmp Low
bcc flip4 if Low <= char <= High
cmp High
beq flip3
bcs flip4
flip3 eor #$20 then flip the case
sta (StrPtr),y
flip4 iny point to next char
bne flip2 loop up to 255 times
flip5 pla restore A
rts return
;------------------------------------------------------
; Output NUL-terminated string @ A:X; strings longer
; than 256 bytes are truncated there
; Uses: StrPtr
; Preserves: A, X
; Trashes: Y
;
puts stx StrPtr init string pointer
sta StrPtr+1
ldy #0
pha save A
puts2 lda (StrPtr),y get string char
beq puts3 done if NUL
jsr CharOut output the char
iny point to next char
bne puts2 loop up to 255 times
puts3 pla restore A
rts return
;------------------------------------------------------
; Test String (in '+128' ascii, Apple II style)
;
sTest .as -"Alpha, BETA, gamma, {[(<123@_>)]}."
.az -#13
;------------------------------------------------------
.en
Output:
Alpha, BETA, gamma, {[(<123@_>)]}.
ALPHA, BETA, GAMMA, {[(<123@_>)]}.
alpha, beta, gamma, {[(<123@_>)]}.
[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
Note: This specimen retains the original C coding style.#!/usr/local/bin/a68g --script #
# Demonstrate toupper and tolower for standard ALGOL 68
strings. This does not work for multibyte character sets. #
INT l2u = ABS "A" - ABS "a";
PROC to upper = (CHAR c)CHAR:
(ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u ));
PROC to lower = (CHAR c)CHAR:
(ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u ));
# Operators can be defined in ALGOL 68 #
OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper;
# upper-cases s in place #
PROC string to upper = (REF STRING s)VOID:
FOR i FROM LWB s TO UPB s DO s[i] := to upper(s[i]) OD;
# lower-cases s in place #
PROC string to lower = (REF STRING s)VOID:
FOR i FROM LWB s TO UPB s DO s[i] := to lower(s[i]) OD;
main: (
STRING t := "alphaBETA";
string to upper(t);
printf(($"uppercase: "gl$, t));
string to lower(t);
printf(($"lowercase: "gl$, t))
)
Output:
uppercase: ALPHABETA lowercase: alphabeta
[edit] APL
a←'abcdefghijklmnopqrstuvwxyz'
A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
X←'alphaBETA'
(a,⎕AV)[(A,⎕AV)⍳'alphaBETA']
alphabeta
(A,⎕AV)[(a,⎕AV)⍳'alphaBETA']
ALPHABETA
In the following example, puntuation is not covered. It is substituted by '*'.
AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ'
AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ*'
AlphUpper[AlphLower⍳'I'm using APL!']
I*M USING APL*
AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ*'
AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ'
AlphLower[AlphUpper⍳'I'm using APL!']
i*m using apl*
[edit] Arbre
main():
uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io
Output:
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] AutoIt
$sString = "alphaBETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sLowercase = StringLower($sString) ;"alphabeta"
[edit] AWK
BEGIN {
a = "alphaBETA";
print toupper(a), tolower(a)
}
Capitalize:
BEGIN {
a = "alphaBETA";
print toupper(substr(a, 1, 1)) tolower(substr(a, 2))
}
[edit] BASIC
s$ = "alphaBETA"
PRINT UCASE$(s$)
PRINT LCASE$(s$)
[edit] BBC BASIC
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$)
Output:
Original: alphaBETA Lower case: alphabeta Upper case: ALPHABETA Title case: AlphaBETA
[edit] Befunge
Converts to uppercase only; lowercase is done in a similar way so I chose not to add it.
"ATEBahpla" > : #v_ 25* , @ >48*-v
> :: "`"` \"{"\` * | > , v
> ^
^ <
[edit] Bracmat
The functions upp$ and low$ assume that strings are UTF-8 encoded, but if a string is not valid UTF-8, it is assumed the string is ISO-8859-1. Case conversion is not restricted to the Latin alphabet, but extends to all alphabets that have upper and lower case characters.
"alphaBETA":?s
& out$str$(upp$!s \n low$!s)
Output:
ALPHABETA alphabeta
[edit] Burlesque
blsq ) "alphaBETA"^^zz\/ZZ
"ALPHABETA"
"alphabeta"
[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#
class Program
{
static void Main(string[] args)
{
string input;
Console.Write("Enter a series of letters: ");
input = Console.ReadLine();
stringCase(input);
}
private static void stringCase(string str)
{
char[] chars = str.ToCharArray();
string newStr = "";
foreach (char i in chars)
if (char.IsLower(i))
newStr += char.ToUpper(i);
else
newStr += char.ToLower(i);
Console.WriteLine("Converted: {0}", newStr);
}
}
Title case is a little different:
System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
[edit] C++
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] Clojure
(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string))
[edit] CMake
string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}")
-- Uppercase: ALPHABETA -- Lowercase: alphabeta
[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 std.stdio, std.string;
void main() {
auto s = "alphaBETA";
writeln(s.toUpper());
writeln(s.toLower());
}
- Output:
ALPHABETA alphabeta
[edit] Delphi
writeln(uppercase('alphaBETA'));
writeln(lowercase('alphaBETA'));
[edit] DWScript
PrintLn(UpperCase('alphaBETA'));
PrintLn(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] Falcon
printl("alphaBETA".lower())
printl("alphaBETA".upper())
[edit] 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
[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 ;
create s ," alphaBETA" s count type s count 2dup upper type s count 2dup lower type
Output:
alphaBETA ALPHABETA alphabeta
[edit] 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
[edit] GML
#define cases
{
x = 'alphaBETA';
y = string_upper(x); // returns ALPHABETA
z = string_lower(x); // returns alphabeta
show_message(y);
show_message(z);
}
[edit] Go
"Title case" in Go's unicode package does not mean capitalize the first letter of each word, but rather capitalize each letter as if it were the first letter of a word. The distinction matters in languages such as Croatian with digraphs with a capitialized form that is different from the all-caps form.
It's the strings package that has the Title function that capitalizes the first letter of each word.
package main
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
func main() {
show("alphaBETA")
show("alpha BETA")
show("DŽLjnj") // should render similar to DZLjnj
}
func show(s string) {
fmt.Println("\nstring: ", s, "len:", utf8.RuneCountInString(s))
fmt.Println("All upper case: ", strings.ToUpper(s)) // DZLJNJ
fmt.Println("All lower case: ", strings.ToLower(s)) // dzljnj
fmt.Println("All title case: ", strings.ToTitle(s)) // DzLjNj
// notice Title() only modifies first letters of words
// non-first letters keep their case.
fmt.Println("Title words: ", strings.Title(s)) // Dzljnj
fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s))
}
Output:
string: alphaBETA len: 9 All upper case: ALPHABETA All lower case: alphabeta All title case: ALPHABETA Title words: AlphaBETA Swapping case: ALPHAbeta string: alpha BETA len: 10 All upper case: ALPHA BETA All lower case: alpha beta All title case: ALPHA BETA Title words: Alpha BETA Swapping case: ALPHA beta string: DŽLjnj len: 3 All upper case: DŽLJNJ All lower case: džljnj All title case: DžLjNj Title words: DžLjnj Swapping case: DžljNJ
[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
procedure main()
write(map("alphaBETA"))
write(map("alphaBETA",&lcase,&ucase))
end
[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());
//Also works with non-English characters with no modification
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß"
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
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] Lua
str = "alphaBETA"
print( string.upper(str) )
print( string.lower(str) )
[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] Mercury
The functions to_upper/1, to_lower/1, capitalize_first/1 and uncapitalize_first/1 only affect unaccented Latin characters.
:- module string_case.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
main(!IO) :-
S = "alphaBETA",
io.format("uppercase : %s\n", [s(to_upper(S))], !IO),
io.format("lowercase : %s\n", [s(to_lower(S))], !IO),
io.format("capitalize first: %s\n", [s(capitalize_first(S))], !IO).
% We can use uncaptitalize_first/1 to ensure the first character in a
% string is lower-case.
[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] mIRC Scripting Language
echo -ag $upper(alphaBETA)
echo -ag $lower(alphaBETA)
[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] 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"));
}
}
[edit] NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols
abc = 'alphaBETA'
say abc.upper
say abc.lower
say abc.upper(1, 1) -- capitalize 1st character
[edit] NewLISP
(upper-case "alphaBETA")
(lower-case "alphaBETA")
[edit] Nial
toupper 'alphaBETA'
=ALPHABETA
tolower 'alphaBETA'
=alphabeta
[edit] Objeck
string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();
[edit] Objective-C
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] OpenEdge/Progress
CAPS("alphaBETA")
LC("alphaBETA")
[edit] OxygenBasic
string s="alphaBETA"
print lcase(s) " "+
ucase(s) " "+
ucase(left(s,1))+mid(s,2) 'capitalised
[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] Pascal
See Delphi
[edit] 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"
Also works in Perl 4 if the my is removed.
[edit] Perl 6
In Perl 6, case modification is implemented as builtin subroutine or method:
my $word = "alpha BETA" ;
say uc $word; # all uppercase (subroutine call)
say $word.uc; # all uppercase (method call)
# from now on we use only method calls as examples
say $word.lc; # all lowercase
say $word.tc; # first letter titlecase
say $word.tclc; # first letter titlecase, rest lowercase
say $word.tcuc; # first letter titlecase, rest uppercase
say $word.wordcase; # capitalize each word
Output:
ALPHA BETA alpha beta Alpha BETA Alpha beta ALPHA BETA Alpha Beta
[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] Racket
#lang racket
(define example "alphaBETA")
(string-upcase example)
;"ALPHABETA"
(string-downcase example)
;"alphabeta"
(string-titlecase example)
;"Alphabeta"
[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] Retro
with strings'
"alphaBETA" toUpper puts
"alphaBETA" toLower puts
[edit] REXX
[edit] version with TRANSLATE BIF
The following code will execute correctly in ASCII and EBCDIC.
abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters*/
abcU = translate(abc) /* " " " uppercase " */
x = 'alphaBETA' /*define string to a REXX variable*/
y = translate(x) /*uppercase X and store it───► Y*/
z = translate(x, abc, abcU) /*tran uppercase──►lowercase chars*/
[edit] version with PARSE UPPER & PARSE LOWER statements
The following code will execute correctly in ASCII and EBCDIC.
x = "alphaBETA" /*define string to a REXX variable*/
parse upper var x y /*uppercase X and store it───► Y*/
parse lower var x z /*lowercase X " " " ───► Z*/
/*Some REXXes don't support the LOWER option for the PARSE command.*/
[edit] version with UPPER & LOWER BIFs
The following code will execute correctly in ASCII and EBCDIC.
x = 'alphaBETA' /*define string to a REXX variable*/
y = upper(x) /*uppercase X and store it───► Y*/
z = lower(x) /*lowercase X " " " ───► Z*/
/*Some REXXes don't support the UPPER and */
/* LOWER BIFs (built-in functions). */
[edit] version with UPPER statement
The following code will execute correctly in ASCII and EBCDIC.
x = "alphaBETA" /*define string to a REXX variable*/
y=x; upper y /*uppercase X and store it───► Y*/
parse lower var x z /*lowercase Y " " " ───► Z*/
/*Some REXXes don't support the LOWER option for the PARSE command.*/
[edit] version with capitalized words
The following code will execute correctly in ASCII and EBCDIC.
/*REXX pgm capitalizes each word in string, maintains imbedded blanks.*/
x= "alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh",
"ayin pe tzadi qof resh shin tav." /*"old" spelling Hebrew letters. */
y= capitalize(x) /*capitalize each word in string.*/
say x /*show original string of words. */
say y /*show the capitalized words. */
exit /*stick a fork in it, we're done.*/
/*───────────────────────────────────CAPITALIZE subroutine──────────────*/
capitalize: procedure; parse arg z; $=' 'z /*prefix with a blank.*/
abc = "abcdefghijklmnopqrstuvwxyz" /*define all lowercase letters. */
do j=1 for 26 /*process each letter in alphabet*/
_=' 'substr(abc,j,1); _U=_; upper _U /*get a lower and upper letter. */
$ = changestr(_, $, _U) /*maybe capitalize some word(s). */
end /*j*/
return substr($,2) /*capitalized words, -1st blank.*/
Some older REXXes don't have a changestr bif, so one is included here ──► CHANGESTR.REX.
output
alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh ayin pe tzadi qof resh shin tav. Alef Bet Gimel Dalet He Vav Zayin Het Tet Yod Kaf Lamed Mem Nun Samekh Ayin Pe Tzadi Qof Resh Shin Tav.
Note: there are many variant spellings of the Hebrew alphabet.
[edit] version with case swap
The following code will execute correctly in ASCII and EBCDIC.
/*REXX pgm swaps letter case of a string: lower──►upper & upper──►lower.*/
abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters*/
abcU = translate(abc) /* " " " uppercase " */
x = 'alphaBETA' /*define string to a REXX variable*/
y = translate(x,abc||abcU,abcU||abc) /*swap case of X store it ───► Y*/
say x
say y
/*stick a fork in it, we're done.*/
output
alphaBETA ALPHAbeta
[edit] version 2
x='alphaBETA'; Say ' x='||x
Say 'three ways to uppercase'
u1=translate(x); Say ' u1='u1
u2=upper(x); Say ' u2='u2
parse upper var x u3; Say ' u3='u3
abc ='abcdefghijklmnopqrstuvwxyz'
abcu=translate(abc); Say 'three ways to lowercase'
l1=translate(x,abc,abcu); Say ' l1='l1
l2=lower(x); Say ' l2='l2
parse lower var x l3; Say ' l3='l3
- Note: Parse options upper and lower not available in every Rexx
- Builtin functions upper and lower not available in every Rexx
- Upper instruction not available in ooRexx
For German input (considering umlaute) these will uppercase them:
uppercase: /*courtesy Gerard Schildberger */
return translate(changestr("ß",translate(arg(1),'ÄÖÜ',"äöü"),'SS'))
uppercase2: Procedure
Parse Arg a
a=translate(arg(1),'ÄÖÜ',"äöü") /* translate lowercase umlaute */
a=changestr("ß",a,'SS') /* replace ß with SS */
return translate(a) /* translate lowercase letters */
Translation to lowercase is not similarly possible because of 'SS'->'ß' or -> 'ss' ??
[edit] Ruby
"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".capitalize # => "Alphabeta"
These methods only affect ASCII letters A-Z and a-z. They ignore any non-ASCII characters.
[edit] Run BASIC
a$ ="alphaBETA"
print a$ '=> alphaBETA
print upper$(a$) '=> ALPHABETA
print lower$(a$) '=> 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)))
Using SRFI-13:
> (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"
[edit] Sed
Piping through sed in bash:
echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
Other functions:
# Invert case
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/'
GNU sed supports special sequences to change case:
# to uppercase
$ echo alphaBETA | sed 's/.*/\U&/'
ALPHABETA
# to lowercase
$ echo alphaBETA | sed 's/.*/\L&/'
alphabeta
[edit] Seed7
writeln(upper("alphaBETA"));
writeln(lower("alphaBETA"));
[edit] Slate
'alphaBETA' toLowercase.
'alphaBETA' toUppercase.
[edit] Smalltalk
'ALPHAbeta' asUppercase "->'ALPHABETA' "
'ALPHAbeta' asLowercase "-> 'alphabeta' "
'alphabeta' asUppercaseFirst "-> 'Alphabeta' "
Unicode (notice, that this cannot be done simply with a straight forward "ch := ch -$a + $A" loop):
(may with others too, but I have not verified)'ĥåçýджк' asUppercase "-> 'ĤÅÇÝДЖК'
[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] SQL
DECLARE @s VARCHAR(10)
SET @s = 'alphaBETA'
print UPPER(@s)
print LOWER(@s)
[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] 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] TI-83 BASIC
Note: While lowercase letters are built in to every TI-83/4/+/SE calculator, typing in lowercase is disabled by default and you have to hack the calculator to type in lowercase. However, the calculator does not have to be hacked to simply display lowercase output from a program, so on non-hacked calculators this program will only be useful one-way. To get lowercase letters, you have to create a new program with "AsmPrgmFDCB24DEC9" as the text, and then execute it on the homescreen with Asm(prgmYOURPROGRAMNAME). Then press [ALPHA] twice.
:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9
:"abcdefghijklmnopqrstuvwxyz"→Str0
:Input ">",Str1
:":"+Str1+":"→Str1
:Prompt U
:If U:Then
:For(I,2,length(Str1))
:If inString(Str0,sub(Str1,I,1)) and sub(Str1,I,1)≠":"
:sub(Str1,1,I-1)+sub(Str9,inString(Str0,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1
:End
:Else
:For(I,2,length(Str1))
:If inString(Str9,sub(Str1,I,1)) and sub(Str1,I,1)≠":"
:sub(Str1,1,I-1)+sub(Str0,inString(Str9,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1
:End
:End
:sub(Str1,2,length(Str1)-2)→Str1
:Pause Str1
[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] TUSCRIPT
$$ MODE TUSCRIPT,{}
string="alphaBETA"
lowercase =EXCHANGE(string," {&a} {-0-} ")
uppercase1=EXCHANGE(string," {&a} {-0+} ")
uppercase2=CAPS (string)
PRINT lowercase
PRINT uppercase1
PRINT uppercase2
Output:
alphabeta ALPHABETA ALPHABETA
[edit] UNIX Shell
For System V tr:
echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA
echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta
For BSD tr, GNU tr, or any POSIX system:
echo alphaBETA | tr a-z A-Z # => ALPHABETA
echo alphaBETA | tr A-Z a-z # => alphabeta
System V has a different syntax, and requires square brackets around ranges. Portable scripts can use System V syntax; the other systems handle square brackets as literal characters, translating [ to [ and ] to ], which is harmless.
[edit] Bash
s="alphaBETA"
echo ${s^^} # => ALPHABETA
echo ${s,,} # => alphabeta
echo ${s^} # => AlphaBETA
[edit] Z Shell
s="alphaBETA"
echo ${s:u} # => ALPHABETA
echo ${s:l} # => alphabeta
[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] Vala
string s = "alphaBeta";
// stores ALPHABETA to string
string s_upper = s.up();
// stores alphabeta to string
string s_lower = s.down();
[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
' Define 's'
Dim s AS String = "alphaBETA"
' Change 's' to Upper Case.
s = s.ToUpper()
' Change 's' to Lower Case.
s = s.ToLower()
[edit] XPL0
string 0; \use zero-terminated string convention
include c:\cxpl\stdlib; \ToUpper, ToLower, and 'code' declarations
proc StrToUpper(S); \Convert string to uppercase characters
char S;
while S(0) do [S(0):= ToUpper(S(0)); S:=S+1];
proc StrToLower(S); \Convert string to lowercase characters
char S;
while S(0) do [S(0):= ToLower(S(0)); S:=S+1];
char Str;
[Str:= "alphaBETA";
StrToUpper(Str);
Text(0, Str); CrLf(0);
StrToLower(Str);
Text(0, Str); CrLf(0);
]
Output:
ALPHABETA alphabeta
- Programming Tasks
- String manipulation
- 4D
- 6502 Assembly
- ActionScript
- Ada
- ALGOL 68
- APL
- Arbre
- AutoHotkey
- AutoIt
- AWK
- BASIC
- BBC BASIC
- Befunge
- Bracmat
- Burlesque
- C
- C sharp
- C++
- STL
- Clojure
- CMake
- ColdFusion
- Common Lisp
- D
- Delphi
- Object Pascal
- DWScript
- E
- Erlang
- F Sharp
- Factor
- Falcon
- Fantom
- Forth
- Fortran
- GML
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Lua
- M4
- Mathematica
- MATLAB
- MAXScript
- Mercury
- Metafont
- MIRC Scripting Language
- Modula-3
- MUMPS
- Nemerle
- NetRexx
- NewLISP
- Nial
- Objeck
- Objective-C
- OCaml
- Octave
- OpenEdge/Progress
- OxygenBasic
- Oz
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- PL/SQL
- Pop11
- Powerbuilder
- PowerShell
- Protium
- PureBasic
- Python
- R
- Racket
- Raven
- REBOL
- Retro
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Sed
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- SQL
- Standard ML
- Tcl
- TI-83 BASIC
- Toka
- TUSCRIPT
- UNIX Shell
- Ursala
- Vala
- VBScript
- Vedit macro language
- Visual Basic .NET
- XPL0
- Openscad/Omit
- PARI/GP/Omit