String case: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add Ecstasy example)
 
(43 intermediate revisions by 22 users not shown)
Line 20: Line 20:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V s = ‘alphaBETA’
<syntaxhighlight lang="11l">V s = ‘alphaBETA’
print(s.uppercase())
print(s.uppercase())
print(s.lowercase())</lang>
print(s.lowercase())</syntaxhighlight>


{{out}}
{{out}}
Line 34: Line 34:
uppercase can be performed with a simple 'OR' with blank character (X'40'), in the same way
uppercase can be performed with a simple 'OR' with blank character (X'40'), in the same way
lowercase can be performed with a 'AND' with character 191 (X'BF').
lowercase can be performed with a 'AND' with character 191 (X'BF').
<lang 360asm>UCASE CSECT
<syntaxhighlight lang="360asm">UCASE CSECT
USING UCASE,R15
USING UCASE,R15
MVC UC,PG
MVC UC,PG
Line 48: Line 48:
LC DS CL(L'PG)
LC DS CL(L'PG)
YREGS
YREGS
END UCASE</lang>
END UCASE</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 58: Line 58:
but now EBCDIC coding with alphabetic in 3 sequences, makes things a bit longer to create
but now EBCDIC coding with alphabetic in 3 sequences, makes things a bit longer to create
translation tables.
translation tables.
<lang 360asm>UCASE CSECT
<syntaxhighlight lang="360asm">UCASE CSECT
USING UCASE,R15
USING UCASE,R15
MVC UC,PG
MVC UC,PG
Line 88: Line 88:
ORG
ORG
YREGS
YREGS
END UCASE</lang>
END UCASE</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 97: Line 97:


=={{header|4D}}==
=={{header|4D}}==
<lang 4d>$string:="alphaBETA"
<syntaxhighlight lang="4d">$string:="alphaBETA"
$uppercase:=Uppercase($string)
$uppercase:=Uppercase($string)
$lowercase:=Lowercase($string)</lang>
$lowercase:=Lowercase($string)</syntaxhighlight>


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==


<lang> .lf case6502.lst
<syntaxhighlight lang="text"> .lf case6502.lst
.cr 6502
.cr 6502
.tf case6502.obj,ap1
.tf case6502.obj,ap1
Line 200: Line 200:
.az -#13
.az -#13
;------------------------------------------------------
;------------------------------------------------------
.en </lang>
.en </syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 209: Line 209:
=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
These algorithms work for any ASCII string. The implementation of actually printing the characters is left out, as it is not actually relevant to this task.
These algorithms work for any ASCII string. The implementation of actually printing the characters is left out, as it is not actually relevant to this task.
<lang 68000devpac>UpperCase:
<syntaxhighlight lang="68000devpac">UpperCase:
;input: A0 = pointer to the string's base address.
;input: A0 = pointer to the string's base address.
;alters the string in-place.
;alters the string in-place.
Line 268: Line 268:
BRA ToggleCase ;next letter
BRA ToggleCase ;next letter
.Terminated:
.Terminated:
RTS</lang>
RTS</syntaxhighlight>


=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
<lang 8080asm> org 100h
<syntaxhighlight lang="8080asm"> org 100h
jmp demo
jmp demo
;;; Convert CP/M string under [HL] to upper case
;;; Convert CP/M string under [HL] to upper case
Line 307: Line 307:
mvi c,9
mvi c,9
jmp 5
jmp 5
str: db 'alphaBETA',13,10,'$'</lang>
str: db 'alphaBETA',13,10,'$'</syntaxhighlight>


{{out}}
{{out}}
Line 314: Line 314:
ALPHABETA
ALPHABETA
alphabeta</pre>
alphabeta</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strcase64.s */


/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Result: \n"
szString: .asciz "alphaBETA"
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 64 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sBuffer: .skip 80
sBuffex1: .skip 80
/************************************/
/* code section */
/************************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x1,qAdrszString
ldr x3,qAdrsBuffer
ldr x4,qAdrsBuffex1
mov x6,#0b100000 // 1 -> bit 5
mov x2,#0
1:
ldrb w0,[x1,x2] // load byte of string
mov x5,x0
cmp x0,#'A' // select alpha characters lower or upper
blt 3f
cmp x0,#'z'
bgt 3f
cmp x0,#'Z'
ble 2f
cmp x0,#'a'
bge 2f
b 3f
2:
orr x0,x0,x6 // converion in lower case (1 -> bit 5)
bic x5,x0,x6 // converion in upper case (0 -> bit 5)
3:
strb w0,[x3,x2] // store lower character
strb w5,[x4,x2] // store upper character
cmp x0,#0 // end string ?
add x2,x2,#1 // increment index character
bne 1b // loop


ldr x0,qAdrszMessResult
bl affichageMess
ldr x0,qAdrsBuffer
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x0,qAdrsBuffex1
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszString: .quad szString
qAdrsBuffer: .quad sBuffer
qAdrsBuffex1: .quad sBuffex1
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessStart: .quad szMessStart
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"

</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Result:
alphabeta
ALPHABETA
</pre>
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit


PROC UpperCase(CHAR ARRAY text,res)
PROC UpperCase(CHAR ARRAY text,res)
Line 350: Line 445:
PrintF("Upper-case string: ""%S""%E",upper)
PrintF("Upper-case string: ""%S""%E",upper)
PrintF("Lower-case string: ""%S""%E",lower)
PrintF("Lower-case string: ""%S""%E",lower)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_case.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_case.png Screenshot from Atari 8-bit computer]
Line 361: Line 456:
=={{header|ActionScript}}==
=={{header|ActionScript}}==


<lang actionscript>var string:String = 'alphaBETA';
<syntaxhighlight lang="actionscript">var string:String = 'alphaBETA';
var upper:String = string.toUpperCase();
var upper:String = string.toUpperCase();
var lower:String = string.toLowerCase();</lang>
var lower:String = string.toLowerCase();</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Characters.Handling, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Characters.Handling, Ada.Text_IO;
use Ada.Characters.Handling, Ada.Text_IO;
use Ada.Characters.Handling, Ada.Text_IO;


Line 374: Line 469:
Put_Line (To_Upper (S));
Put_Line (To_Upper (S));
Put_Line (To_Lower (S));
Put_Line (To_Lower (S));
end Upper_Case_String;</lang>
end Upper_Case_String;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 381: Line 476:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<lang algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #


# Demonstrate toupper and tolower for standard ALGOL 68
# Demonstrate toupper and tolower for standard ALGOL 68
Line 411: Line 506:
string to lower(t);
string to lower(t);
printf(($"lowercase: "gl$, t))
printf(($"lowercase: "gl$, t))
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 419: Line 514:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% algol W doesn't have standard case conversion routines, this is one way %
% algol W doesn't have standard case conversion routines, this is one way %
% such facilities could be provided %
% such facilities could be provided %
Line 460: Line 555:
write( text( 0 // 40 ) );
write( text( 0 // 40 ) );


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 468: Line 563:


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#include <hopper.h>


Line 504: Line 599:
{_X_} // put processed string into the stack...
{_X_} // put processed string into the stack...
back
back
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 547: Line 642:
{{works with|APL}}
{{works with|APL}}
In the following example, puntuation is not covered. It is substituted by '*'.
In the following example, puntuation is not covered. It is substituted by '*'.
<lang apl>
<syntaxhighlight lang="apl">
AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ'
AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ'
AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ*'
AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ*'
Line 557: Line 652:
AlphLower[AlphUpper⍳'I'm using APL!']
AlphLower[AlphUpper⍳'I'm using APL!']
i*m using apl*
i*m using apl*
</syntaxhighlight>
</lang>
==={{header|APL (Dyalog)}}===
==={{header|APL (Dyalog)}}===
Dyalog APL has a system function for case conversion, <code>⎕C</code>. This is Unicode-aware and preserves punctuation. If called monadically, maps character arrays to lower case. If called with a left-hand argument of 1, maps character arrays to upper case.
Dyalog APL has a system function for case conversion, <code>⎕C</code>. This is Unicode-aware and preserves punctuation. If called monadically, maps character arrays to lower case. If called with a left-hand argument of 1, maps character arrays to upper case.
<syntaxhighlight lang="apl">
<lang APL>
⎕C 'Πέτρος is using APL!'
⎕C 'Πέτρος is using APL!'
πέτροσ is using apl!
πέτροσ is using apl!
1 ⎕C 'Πέτρος is using APL!'
1 ⎕C 'Πέτρος is using APL!'
ΠΈΤΡΟΣ IS USING APL!
ΠΈΤΡΟΣ IS USING APL!
</syntaxhighlight>
</lang>


Note: The I-Beam operator with code 819 is now deprecated in favor of the system function <code>⎕C</code>.
Note: The I-Beam operator with code 819 is now deprecated in favor of the system function <code>⎕C</code>.
Line 574: Line 669:
AppleScript lacks built in string case functions, but since OS X 10.10 (Yosemite version, Oct 2014) it has been possible to use ObjC Foundation class methods directly in AppleScript code.
AppleScript lacks built in string case functions, but since OS X 10.10 (Yosemite version, Oct 2014) it has been possible to use ObjC Foundation class methods directly in AppleScript code.


<lang applescript>use framework "Foundation"
<syntaxhighlight lang="applescript">use framework "Foundation"


-- TEST -----------------------------------------------------------------------
-- TEST -----------------------------------------------------------------------
Line 634: Line 729:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}</lang>
<syntaxhighlight lang="applescript">{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}</syntaxhighlight>


=={{header|Arbre}}==
=={{header|Arbre}}==
<lang arbre>main():
<syntaxhighlight lang="arbre">main():
uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io</lang>
uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 646: Line 741:
alphabeta
alphabeta
</pre>
</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program strcase.s */


/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../constantes.inc"

/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Result: \n"
szString: .asciz "alphaBETA"
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 32 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sBuffer: .skip 80
sBuffer1: .skip 80
/************************************/
/* code section */
/************************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r1,iAdrszString
ldr r3,iAdrsBuffer
ldr r4,iAdrsBuffer1
mov r6,#0b100000 @ 1 -> bit 5
mov r2,#0
1:
ldrb r0,[r1,r2] @ load byte of string
mov r5,r0
cmp r0,#'A' @ select alpha characters lower or upper
blt 3f
cmp r0,#'z'
bgt 3f
cmp r0,#'Z'
ble 2f
cmp r0,#'a'
bge 2f
b 3f
2:
orr r0,r0,r6 @ converion in lower case (1 -> bit 5)
bic r5,r0,r6 @ converion in upper case (0 -> bit 5)
3:
strb r0,[r3,r2] @ store lower character
strb r5,[r4,r2] @ store upper character
cmp r0,#0 @ end string ?
add r2,r2,#1 @ increment index character
bne 1b @ loop


ldr r0,iAdrszMessResult
bl affichageMess
ldr r0,iAdrsBuffer
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrsBuffer1
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszString: .int szString
iAdrsBuffer: .int sBuffer
iAdrsBuffer1: .int sBuffer1
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessStart: .int szMessStart
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"

</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
Result:
alphabeta
ALPHABETA
</pre>
=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>str: "alphaBETA"
<syntaxhighlight lang="rebol">str: "alphaBETA"


print ["uppercase :" upper str]
print ["uppercase :" upper str]
print ["lowercase :" lower str]
print ["lowercase :" lower str]
print ["capitalize :" capitalize str]</lang>
print ["capitalize :" capitalize str]</syntaxhighlight>


{{out}}
{{out}}
Line 662: Line 852:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


<lang autohotkey>a := "alphaBETA"
<syntaxhighlight lang="autohotkey">a := "alphaBETA"
StringLower, b, a ; alphabeta
StringLower, b, a ; alphabeta
StringUpper, c, a ; ALPHABETA
StringUpper, c, a ; ALPHABETA


StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"</lang>
StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==


<lang autoit>$sString = "alphaBETA"
<syntaxhighlight lang="autoit">$sString = "alphaBETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sLowercase = StringLower($sString) ;"alphabeta"</lang>
$sLowercase = StringLower($sString) ;"alphabeta"</syntaxhighlight>


=={{header|Avail}}==
=={{header|Avail}}==


<lang Avail>Print: uppercase "alphaBETA";
<syntaxhighlight lang="avail">Print: uppercase "alphaBETA";
Print: lowercase "alphaBETA";</lang>
Print: lowercase "alphaBETA";</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
a = "alphaBETA";
a = "alphaBETA";
print toupper(a), tolower(a)
print toupper(a), tolower(a)
}</lang>
}</syntaxhighlight>


Capitalize:
Capitalize:
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
a = "alphaBETA";
a = "alphaBETA";
print toupper(substr(a, 1, 1)) tolower(substr(a, 2))
print toupper(substr(a, 1, 1)) tolower(substr(a, 2))
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
{{works with|QBasic}}
<lang qbasic>s$ = "alphaBETA"
<syntaxhighlight lang="qbasic">s$ = "alphaBETA"
PRINT UCASE$(s$)
PRINT UCASE$(s$)
PRINT LCASE$(s$)</lang>
PRINT LCASE$(s$)</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>S$ = "alphaBETA"
<syntaxhighlight lang="applesoftbasic">S$ = "alphaBETA"


UP$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : UP$ = UP$ + CHR$(C - (C > 96 AND C < 123) * 32) : NEXT I : ? UP$
UP$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : UP$ = UP$ + CHR$(C - (C > 96 AND C < 123) * 32) : NEXT I : ? UP$


LO$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : LO$ = LO$ + CHR$(C + (C > 64 AND C < 91) * 32) : NEXT I : ? LO$</lang>
LO$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : LO$ = LO$ + CHR$(C + (C > 64 AND C < 91) * 32) : NEXT I : ? LO$</syntaxhighlight>

==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">s$ = "alphaBETA"
print "Original string: "; s$
print "To Lower case: "; lower(s$)
print "To Upper case: "; upper(s$)</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"STRINGLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"STRINGLIB"
original$ = "alphaBETA"
original$ = "alphaBETA"
Line 713: Line 909:
PRINT "Lower case: " FN_lower(original$)
PRINT "Lower case: " FN_lower(original$)
PRINT "Upper case: " FN_upper(original$)
PRINT "Upper case: " FN_upper(original$)
PRINT "Title case: " FN_title(original$)</lang>
PRINT "Title case: " FN_title(original$)</syntaxhighlight>
Output:
Output:
<pre>Original: alphaBETA
<pre>Original: alphaBETA
Line 720: Line 916:
Title case: AlphaBETA</pre>
Title case: AlphaBETA</pre>


==={{header|Commodore BASIC}}===
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 s$ = "alphaBETA"
20 print "Original string: ";s$
30 print "To Lower case: ";lcase$(s$)
40 print "To Upper case: ";ucase$(s$)</syntaxhighlight>


==={{header|Commodore BASIC}}===
The example here is based on AppleSoft BASIC, however, Commodore machines have a slightly different interpretation of ASCII:
The example here is based on AppleSoft BASIC, however, Commodore machines have a slightly different interpretation of ASCII:


Line 734: Line 936:


'''Code Example'''
'''Code Example'''
<lang commodorebasic>10 rem string case
<syntaxhighlight lang="commodorebasic">10 rem string case
15 rem rosetta code
15 rem rosetta code
20 s$="alphaBETA"
20 s$="alphaBETA"
Line 747: Line 949:
75 next i
75 next i
80 print:print "Uppercase: ";up$
80 print:print "Uppercase: ";up$
90 print "Lowercase: ";lo$</lang>
90 print "Lowercase: ";lo$</syntaxhighlight>


{{output}}
{{output}}
Line 760: Line 962:
ready.
ready.
&#9608;</pre>
&#9608;</pre>

==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64

Dim s As String = "alphaBETA"
Print UCase(s)
Print LCase(s)
Sleep</syntaxhighlight>

{{out}}
<pre>
ALPHABETA
alphabeta
</pre>

==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1

CFStringRef s = @"alphaBETA"

print s
print ucase(s)
print lcase(s)

HandleEvents</syntaxhighlight>

Output:
<pre>
alphaBETA
ALPHABETA
alphabeta
</pre>

==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=d45e91bee011314fd126dc53052b5386 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String = "alphaBETA "

Print UCase(sString)
Print LCase(sString)

End</syntaxhighlight>
Output:
<pre>
ALPHABETA
alphabeta
</pre>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 INPUT PROMPT "String: ":TX$
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "String: ":TX$
110 PRINT "Lower case: ";LCASE$(TX$)
110 PRINT "Lower case: ";LCASE$(TX$)
120 PRINT "Upper case: ";UCASE$(TX$)</lang>
120 PRINT "Upper case: ";UCASE$(TX$)</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<lang lb>
{{works with|Run BASIC}}
<syntaxhighlight lang="lb">
input$ ="alphaBETA"
input$ ="alphaBETA"


Line 775: Line 1,026:


end
end
</syntaxhighlight>
</lang>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
<lang PureBasic>s$ = "alphaBETA"
<syntaxhighlight lang="purebasic">s$ = "alphaBETA"
upper$ = UCase(s$) ;uppercase
upper$ = UCase(s$) ;uppercase
lower$ = LCase(s$) ;lowercase</lang>
lower$ = LCase(s$) ;lowercase</syntaxhighlight>

==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case: "; LCASE$(s$)
PRINT "To Upper case: "; UCASE$(s$)</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<lang runbasic>a$ ="alphaBETA"
{{works with|Liberty BASIC}}
<syntaxhighlight lang="runbasic">a$ ="alphaBETA"
print a$ '=> alphaBETA
print a$ '=> alphaBETA
print upper$(a$) '=> ALPHABETA
print upper$(a$) '=> ALPHABETA
print lower$(a$) '=> alphabeta</lang>
print lower$(a$) '=> alphabeta</syntaxhighlight>


==={{header|TI-83 BASIC}}===
==={{header|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.
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.

==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case: "; LCASE$(s$)
PRINT "To Upper case: "; UCASE$(s$)
END</syntaxhighlight>

==={{header|Visual Basic}}===
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">Sub Main()
Const TESTSTRING As String = "alphaBETA"
Debug.Print "initial = " _
& TESTSTRING
Debug.Print "uppercase = " _
& UCase(TESTSTRING)
Debug.Print "lowercase = " _
& LCase(TESTSTRING)
Debug.Print "first letter capitalized = " _
& StrConv(TESTSTRING, vbProperCase)
Debug.Print "length (in characters) = " _
& CStr(Len(TESTSTRING))
Debug.Print "length (in bytes) = " _
& CStr(LenB(TESTSTRING))
Debug.Print "reversed = " _
& StrReverse(TESTSTRING)
Debug.Print "first position of letter A (case-sensitive) = " _
& InStr(1, TESTSTRING, "A", vbBinaryCompare)
Debug.Print "first position of letter A (case-insensitive) = " _
& InStr(1, TESTSTRING, "A", vbTextCompare)
Debug.Print "concatenated with '123' = " _
& TESTSTRING & "123"
End Sub</syntaxhighlight>
{{out}}
<pre>initial = alphaBETA
uppercase = ALPHABETA
lowercase = alphabeta
first letter capitalized = Alphabeta
length (in characters) = 9
length (in bytes) = 18
reversed = ATEBahpla
first position of letter A (case-sensitive) = 9
first position of letter A (case-insensitive) = 1
concatenated with '123' = alphaBETA123</pre>


==={{header|Visual Basic .NET}}===
==={{header|Visual Basic .NET}}===
{{works with|Visual Basic|2008}}
{{works with|Visual Basic|2008}}
<lang vbnet>' Define 's'
<syntaxhighlight lang="vbnet">' Define 's'
Dim s AS String = "alphaBETA"
Dim s AS String = "alphaBETA"


Line 801: Line 1,106:


' Change 's' to Lower Case.
' Change 's' to Lower Case.
s = s.ToLower()</lang>
s = s.ToLower()</syntaxhighlight>


<lang ti83b>:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9
<syntaxhighlight lang="ti83b">:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9
:"abcdefghijklmnopqrstuvwxyz"→Str0
:"abcdefghijklmnopqrstuvwxyz"→Str0
:Input ">",Str1
:Input ">",Str1
Line 820: Line 1,125:
:End
:End
:sub(Str1,2,length(Str1)-2)→Str1
:sub(Str1,2,length(Str1)-2)→Str1
:Pause Str1</lang>
:Pause Str1</syntaxhighlight>

==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "StringCase"
VERSION "0.0000"

DECLARE FUNCTION Entry ()

FUNCTION Entry ()
s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case: "; LCASE$(s$)
PRINT "To Upper case: "; UCASE$(s$)

END FUNCTION
END PROGRAM</syntaxhighlight>

==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">s$ = "alphaBETA"
print "Original string: ", s$
print "To Lower case: ", lower$(s$)
print "To Upper case: ", upper$(s$)</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang BCPL>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


// Check whether a character is an upper or lowercase letter
// Check whether a character is an upper or lowercase letter
Line 848: Line 1,175:
writef("Uppercase: %S*N", strtoupper(s))
writef("Uppercase: %S*N", strtoupper(s))
writef("Lowercase: %S*N", strtolower(s))
writef("Lowercase: %S*N", strtolower(s))
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre> String: alphaBETA
<pre> String: alphaBETA
Uppercase: ALPHABETA
Uppercase: ALPHABETA
Lowercase: alphabeta</pre>
Lowercase: alphabeta</pre>


=={{header|Beef}}==
<syntaxhighlight lang="csharp">
using System;

namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
</syntaxhighlight>
{{out}}
<pre>ALPHABETA
alphabeta</pre>


=={{header|Befunge}}==
=={{header|Befunge}}==
{{works with|befungee}}
{{works with|befungee}}
Converts to uppercase only; lowercase is done in a similar way so I chose not to add it.
Converts to uppercase only; lowercase is done in a similar way so I chose not to add it.
<lang Befunge>"ATEBahpla" > : #v_ 25* , @ >48*-v
<syntaxhighlight lang="befunge">"ATEBahpla" > : #v_ 25* , @ >48*-v
> :: "`"` \"{"\` * | > , v
> :: "`"` \"{"\` * | > , v
> ^
> ^
^ <</lang>
^ <</syntaxhighlight>

=={{header|BQN}}==
Both idioms are from BQNcrate. For reference, <code>⍋</code> in both examples performs a binary search to check if the characters are in the respective alphabet range. Based on that, the correct number is added at those locations to change case.
<syntaxhighlight lang="bqn">Upr ← -⟜(32×1="a{"⊸⍋) # Uppercase ASCII text
Lwr ← +⟜(32×1="A["⊸⍋) # Lowercase ASCII text</syntaxhighlight>
<syntaxhighlight> str ← "alphaBETA"
"alphaBETA"
Upr str
"ALPHABETA"
Lwr str
"alphabeta"</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
The functions <code>upp$</code> and <code>low$</code> 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.
The functions <code>upp$</code> and <code>low$</code> 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.
<lang bracmat> "alphaBETA":?s
<syntaxhighlight lang="bracmat"> "alphaBETA":?s
& out$str$(upp$!s \n low$!s)</lang>
& out$str$(upp$!s \n low$!s)</syntaxhighlight>
Output:
Output:
<pre>ALPHABETA
<pre>ALPHABETA
Line 872: Line 1,234:
=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) "alphaBETA"^^zz\/ZZ
blsq ) "alphaBETA"^^zz\/ZZ
"ALPHABETA"
"ALPHABETA"
"alphabeta"
"alphabeta"
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
The <tt>tolower</tt> and <tt>toupper</tt> functions are locale-aware.
The <tt>tolower</tt> and <tt>toupper</tt> functions are locale-aware.
<lang c>/* Demonstrate toupper and tolower for
<syntaxhighlight lang="c">/* Demonstrate toupper and tolower for
standard C strings.
standard C strings.
This does not work for multibyte character sets. */
This does not work for multibyte character sets. */
Line 915: Line 1,277:
printf("lowercase: %s\n", t);
printf("lowercase: %s\n", t);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>
<syntaxhighlight lang="csharp">
class Program
class Program
{
{
Line 942: Line 1,304:
Console.WriteLine("Converted: {0}", newStr);
Console.WriteLine("Converted: {0}", newStr);
}
}
}</lang>
}</syntaxhighlight>


Title case is a little different:
Title case is a little different:
<lang csharp>System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));</lang>
<syntaxhighlight lang="csharp">System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 954: Line 1,316:
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.


<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <string>
#include <string>
#include <cctype>
#include <cctype>
Line 974: Line 1,336:
str.begin(),
str.begin(),
(int(*)(int)) std::tolower);
(int(*)(int)) std::tolower);
}</lang>
}</syntaxhighlight>


Here is sample usage code:
Here is sample usage code:


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <string>


Line 989: Line 1,351:
cout << foo << endl;
cout << foo << endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(def string "alphaBETA")
<syntaxhighlight lang="lisp">(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toUpperCase string))
(println (.toLowerCase string))</lang>
(println (.toLowerCase string))</syntaxhighlight>


=={{header|CMake}}==
=={{header|CMake}}==
<lang cmake>string(TOUPPER alphaBETA s)
<syntaxhighlight lang="cmake">string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}")</lang>
message(STATUS "Lowercase: ${s}")</syntaxhighlight>


<pre>-- Uppercase: ALPHABETA
<pre>-- Uppercase: ALPHABETA
Line 1,007: Line 1,369:
=={{header|COBOL}}==
=={{header|COBOL}}==
===Standard-compliant Methods===
===Standard-compliant Methods===
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. string-case-85.
PROGRAM-ID. string-case-85.


Line 1,036: Line 1,398:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


===Compiler Extensions===
===Compiler Extensions===
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. string-case-extensions.
PROGRAM-ID. string-case-extensions.


Line 1,070: Line 1,432:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==


converting a string literal
converting a string literal
<lang coldfusion><cfset upper = UCase("alphaBETA")>
<syntaxhighlight lang="coldfusion"><cfset upper = UCase("alphaBETA")>
<cfset lower = LCase("alphaBETA")></lang>
<cfset lower = LCase("alphaBETA")></syntaxhighlight>


converting the value of a variable
converting the value of a variable
<lang coldfusion><cfset string = "alphaBETA">
<syntaxhighlight lang="coldfusion"><cfset string = "alphaBETA">
<cfset upper = UCase(string)>
<cfset upper = UCase(string)>
<cfset lower = LCase(string)></lang>
<cfset lower = LCase(string)></syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
You can use the ''string-upcase'' function to perform upper casing:
You can use the ''string-upcase'' function to perform upper casing:


<lang lisp>CL-USER> (string-upcase "alphaBETA")
<syntaxhighlight lang="lisp">CL-USER> (string-upcase "alphaBETA")
"ALPHABETA"</lang>
"ALPHABETA"</syntaxhighlight>


and you can do lower casing by using ''string-downcase'':
and you can do lower casing by using ''string-downcase'':


<lang lisp>CL-USER> (string-downcase "alphaBETA")
<syntaxhighlight lang="lisp">CL-USER> (string-downcase "alphaBETA")
"alphabeta"</lang>
"alphabeta"</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE AlphaBeta;
MODULE AlphaBeta;
IMPORT StdLog,Strings;
IMPORT StdLog,Strings;
Line 1,112: Line 1,474:


END AlphaBeta.
END AlphaBeta.
</syntaxhighlight>
</lang>
Execute: ^Q AlphaBeta.Do<br/>
Execute: ^Q AlphaBeta.Do<br/>
Output:
Output:
Line 1,119: Line 1,481:
Lowercase:> alphabeta
Lowercase:> alphabeta
</pre>
</pre>

=={{header|Crystal}}==
<syntaxhighlight lang="crystal">"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"

"alphaBETA".capitalize # => "Alphabeta"</syntaxhighlight>

Fully works with all Unicode range.

<syntaxhighlight lang="crystal">"ĥåçýджк".upcase # => "ĤÅÇÝДЖК"</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.string;
import std.stdio, std.string;


Line 1,127: Line 1,499:
s.toUpper.writeln;
s.toUpper.writeln;
s.toLower.writeln;
s.toLower.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>ALPHABETA
<pre>ALPHABETA
alphabeta</pre>
alphabeta</pre>


=={{header|Dart}}==
<syntaxhighlight lang="dart">String capitalize(String string) {
if (string.isEmpty) {
return string;
}
return string[0].toUpperCase() + string.substring(1);
}

void main() {
var s = 'alphaBETA';
print('Original string: $s');
print('To Lower case: ${s.toLowerCase()}');
print('To Upper case: ${s.toUpperCase()}');
print('To Capitalize: ${capitalize(s)}');
}</syntaxhighlight>
{{out}}
<pre>Original string: alphaBETA
To Lower case: alphabeta
To Upper case: ALPHABETA
To Capitalize: AlphaBETA</pre>


=={{header|DBL}}==
=={{header|DBL}}==
<syntaxhighlight lang="dbl">
<lang DBL>
OPEN (1,O,'TT:') ;open video
OPEN (1,O,'TT:') ;open video


Line 1,143: Line 1,535:


UPCASE STR
UPCASE STR
DISPLAY (1,STR,10) ;ALPHABETA</lang>
DISPLAY (1,STR,10) ;ALPHABETA</syntaxhighlight>


=={{header|Delphi}}[[Category:Object Pascal]]==
=={{header|Delphi}}[[Category:Object Pascal]]==
<lang pascal>writeln(uppercase('alphaBETA'));
<syntaxhighlight lang="pascal">writeln(uppercase('alphaBETA'));
writeln(lowercase('alphaBETA'));</lang>
writeln(lowercase('alphaBETA'));</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang delphi>PrintLn(UpperCase('alphaBETA'));
<syntaxhighlight lang="delphi">PrintLn(UpperCase('alphaBETA'));
PrintLn(LowerCase('alphaBETA'));</lang>
PrintLn(LowerCase('alphaBETA'));</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>let str = "alphaBETA"
<syntaxhighlight lang="dyalect">let str = "alphaBETA"
print("Lower case: ", str.Lower(), separator: "")
print("Lower case: ", str.Lower(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Capitalize: ", str.Capitalize(), separator: "")</lang>
print("Capitalize: ", str.Capitalize(), separator: "")</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
<lang e>["alphaBETA".toUpperCase(),
<syntaxhighlight lang="e">["alphaBETA".toUpperCase(),
"alphaBETA".toLowerCase()]</lang>
"alphaBETA".toLowerCase()]</syntaxhighlight>

=={{header|EasyLang}}==
EasyLang does not have string case functions. The functions provided below only work with ASCII.
<syntaxhighlight lang="easylang">
func$ toUpper s$ .
for c$ in strchars s$
code = strcode c$
if code >= 97 and code <= 122
code -= 32
.
res$ &= strchar code
.
return res$
.
func$ toLower s$ .
for c$ in strchars s$
code = strcode c$
if code >= 65 and code <= 90
code += 32
.
res$ &= strchar code
.
return res$
.
string$ = "alphaBETA"
print string$
print toUpper string$
print toLower string$
</syntaxhighlight>
{{out}}
<pre>
alphaBETA
ALPHABETA
alphabeta
</pre>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
EchoLisp includes the usual case conversion functions and the '''randcase''' function : random case
EchoLisp includes the usual case conversion functions and the '''randcase''' function : random case
<lang scheme>
<syntaxhighlight lang="scheme">
(string-downcase "alphaBETA")
(string-downcase "alphaBETA")
→ "alphabeta"
→ "alphabeta"
Line 1,178: Line 1,605:
(string-randcase "alphaBETA")
(string-randcase "alphaBETA")
→ "AlPHaBeTA"
→ "AlPHaBeTA"
</syntaxhighlight>
</lang>


=={{header|ECL}}==
=={{header|ECL}}==
<lang ECL>IMPORT STD; //Imports the Standard Library
<syntaxhighlight lang="ecl">IMPORT STD; //Imports the Standard Library


STRING MyBaseString := 'alphaBETA';
STRING MyBaseString := 'alphaBETA';
Line 1,191: Line 1,618:
OUTPUT (UpperCased);
OUTPUT (UpperCased);
OUTPUT (LowerCased);
OUTPUT (LowerCased);
OUTPUT (TitleCased);</lang>
OUTPUT (TitleCased);</syntaxhighlight>

=={{header|Ecstasy}}==
The methods on <code>String</code> are <code>toUppercase()</code> and <code>toLowercase()</code>:

<syntaxhighlight lang="ecstasy">
module test {
void run() {
@Inject Console console;
console.print($"{"alphaBETA".toLowercase()=}");
console.print($"{"alphaBETA".toUppercase()=}");
}
}
</syntaxhighlight>

{{out}}
<pre>
x$ xec test
"alphaBETA".toLowercase()=alphabeta
"alphaBETA".toUppercase()=ALPHABETA
</pre>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x:
ELENA 6.x:
<lang elena>import system'culture;
<syntaxhighlight lang="elena">import system'culture;
public program()
public program()
Line 1,201: Line 1,648:
string s1 := "alphaBETA";
string s1 := "alphaBETA";
// Alternative 1
console.writeLine(s1.lowerCase());
console.writeLine(s1.upperCase());
// Alternative 2
console.writeLine(s1.toLower(currentLocale));
console.writeLine(s1.toLower(currentLocale));
console.writeLine(s1.toUpper(currentLocale));
console.writeLine(s1.toUpper(currentLocale));
console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
The String module provides the following functions:
The String module provides the following functions:
<lang elixir>
<syntaxhighlight lang="elixir">
String.downcase("alphaBETA")
String.downcase("alphaBETA")
# => alphabeta
# => alphabeta
Line 1,220: Line 1,662:
String.capitalize("alphaBETA")
String.capitalize("alphaBETA")
# => Alphabeta
# => Alphabeta
</syntaxhighlight>
</lang>
As with most String functions in Elixir, these are fully compatible with Unicode.
As with most String functions in Elixir, these are fully compatible with Unicode.
<lang elixir>
<syntaxhighlight lang="elixir">
String.downcase("αΒ")
String.downcase("αΒ")
# => αβ
# => αβ
Line 1,229: Line 1,671:
String.capitalize("αΒ")
String.capitalize("αΒ")
# => Αβ
# => Αβ
String.upcase("ß")
</lang>
# => SS
</syntaxhighlight>


=={{header|Elm}}==
=={{header|Elm}}==
<lang elm>import String exposing (toLower, toUpper)
<syntaxhighlight lang="elm">import String exposing (toLower, toUpper)


s = "alphaBETA"
s = "alphaBETA"
lower = toLower s
lower = toLower s
upper = toUpper s</lang>
upper = toUpper s</syntaxhighlight>

=={{header|EMal}}==

<syntaxhighlight lang="emal">
var samples = text["alphaBETA", "ação", "o'hare O'HARE o’hare don't", "Stroßbùrri", "ĥåçýджк", "DŽLjnj"]
for each var sample in samples
writeLine(" original : " + sample)
writeLine(" lower : " + sample.lower())
writeLine(" upper : " + sample.upper())
writeLine()
end
</syntaxhighlight>
{{out}}
<pre>
original : alphaBETA
lower : alphabeta
upper : ALPHABETA

original : ação
lower : ação
upper : AÇÃO

original : o'hare O'HARE o’hare don't
lower : o'hare o'hare o’hare don't
upper : O'HARE O'HARE O’HARE DON'T

original : Stroßbùrri
lower : stroßbùrri
upper : STROßBÙRRI

original : ĥåçýджк
lower : ĥåçýджк
upper : ĤÅÇÝДЖК

original : DŽLjnj
lower : džljnj
upper : DŽLJNJ

</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>string:to_upper("alphaBETA").
<syntaxhighlight lang="erlang">string:to_upper("alphaBETA").
string:to_lower("alphaBETA").</lang>
string:to_lower("alphaBETA").</syntaxhighlight>


=={{header|Excel}}==
=={{header|Excel}}==
Take 3 cells, say A1,B1 and C1. In B1 type :
Take 3 cells, say A1,B1 and C1. In B1 type :


<lang excel>
<syntaxhighlight lang="excel">
=LOWER(A1)
=LOWER(A1)
</syntaxhighlight>
</lang>


and in C1 :
and in C1 :


<lang excel>
<syntaxhighlight lang="excel">
=UPPER(A1)
=UPPER(A1)
</syntaxhighlight>
</lang>


For the stated input in A1, the result will be :
For the stated input in A1, the result will be :


<lang>
<syntaxhighlight lang="text">
alphaBETA alphabeta ALPHABETA
alphaBETA alphabeta ALPHABETA
</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let s = "alphaBETA"
let s = "alphaBETA"
let upper = s.ToUpper()
let upper = s.ToUpper()
let lower = s.ToLower()
let lower = s.ToLower()
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"alphaBETA" >lower ! "alphabeta"
<syntaxhighlight lang="factor">"alphaBETA" >lower ! "alphabeta"
"alphaBETA" >upper ! "ALPHABETA"
"alphaBETA" >upper ! "ALPHABETA"
"alphaBETA" >title ! "Alphabeta"
"alphaBETA" >title ! "Alphabeta"
"ß" >case-fold ! "ss"</lang>
"ß" >case-fold ! "ss"</syntaxhighlight>


=={{header|Falcon}}==
=={{header|Falcon}}==


<lang falcon>printl("alphaBETA".lower())
<syntaxhighlight lang="falcon">printl("alphaBETA".lower())
printl("alphaBETA".upper())</lang>
printl("alphaBETA".upper())</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
fansh> a := "alphaBETA"
fansh> a := "alphaBETA"
alphaBETA
alphaBETA
Line 1,293: Line 1,776:
fansh> "BETAalpha".decapitalize // make sure first letter is not capital
fansh> "BETAalpha".decapitalize // make sure first letter is not capital
bETAalpha
bETAalpha
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 1,321: Line 1,804:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran> program example
<syntaxhighlight lang="fortran"> program example
implicit none
implicit none
Line 1,358: Line 1,841:
end subroutine To_Lower
end subroutine To_Lower


end program example</lang>
end program example</syntaxhighlight>


Functions could be used instead, especially with later compilers that enable lengths not fixed at compile time, but this involves copying the text about. By contrast, the subroutines alter the text in-place, though if something like <code>Utext = Uppercase(text)</code> is desired so that both versions are available, a subroutine is less convenient.
Functions could be used instead, especially with later compilers that enable lengths not fixed at compile time, but this involves copying the text about. By contrast, the subroutines alter the text in-place, though if something like <code>Utext = Uppercase(text)</code> is desired so that both versions are available, a subroutine is less convenient.
Line 1,364: Line 1,847:
F90 introduced the intrinsic function i = I'''A'''CHAR(c), which returns the integer value of the position of character c ''in the'' '''ASCII''' character set, even if the processor's default character set is different, such as perhaps '''EBCDIC'''. Function ACHAR is the inverse. If the bit pattern of the character was not being interpreted as in the ASCII set, this will cause odd results, say on a system using EBCDIC or (on an ASCII-using cpu) for a file originating from an EBCDIC-using system. Some systems offer additional options to the file OPEN statement that enable character conversion between ASCII and EBCDIC, and there may also be options concerning big- and little-endian usage. But much will depend on the format of the data in the file. If the data are a mixture of text, integers, floating-point, ''etc.'' all in binary, there will be no hope for such simple translations.
F90 introduced the intrinsic function i = I'''A'''CHAR(c), which returns the integer value of the position of character c ''in the'' '''ASCII''' character set, even if the processor's default character set is different, such as perhaps '''EBCDIC'''. Function ACHAR is the inverse. If the bit pattern of the character was not being interpreted as in the ASCII set, this will cause odd results, say on a system using EBCDIC or (on an ASCII-using cpu) for a file originating from an EBCDIC-using system. Some systems offer additional options to the file OPEN statement that enable character conversion between ASCII and EBCDIC, and there may also be options concerning big- and little-endian usage. But much will depend on the format of the data in the file. If the data are a mixture of text, integers, floating-point, ''etc.'' all in binary, there will be no hope for such simple translations.


For converting lower-case text to upper, the following will work both on an ASCII system and an EBCDIC system (or any other encodement), once it is compiled for that system: <lang Fortran> SUBROUTINE UPCASE(TEXT)
For converting lower-case text to upper, the following will work both on an ASCII system and an EBCDIC system (or any other encodement), once it is compiled for that system: <syntaxhighlight lang="fortran"> SUBROUTINE UPCASE(TEXT)
CHARACTER*(*) TEXT
CHARACTER*(*) TEXT
INTEGER I,C
INTEGER I,C
Line 1,371: Line 1,854:
IF (C.GT.0) TEXT(I:I) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"(C:C)
IF (C.GT.0) TEXT(I:I) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"(C:C)
END DO
END DO
END</lang>
END</syntaxhighlight>
The INDEX function of course returning zero if the character is not found. Converting from upper to lower case is the obvious inverse and it might be worthwhile defining a MODULE with suitable named character constants to avoid repetition - one might hope the compiler will share duplicated constants rather than producing a fresh version every time, but it might not too. The repeated text scanning done by the INDEX function for each character of TEXT will of course be a lot slower. A still-more advanced compiler might be able to take advantage of special translation op-codes, on systems that offer them. If storage space is not at a premium a swifter method would be to create something like <code>CHARACTER*1 XLATUC(0:255)</code> with most entries being equal to their index, except for those corresponding to the lower case letters for which the value is the corresponding upper case letter. Then <lang Fortran> DO I = 1,LEN(TEXT)
The INDEX function of course returning zero if the character is not found. Converting from upper to lower case is the obvious inverse and it might be worthwhile defining a MODULE with suitable named character constants to avoid repetition - one might hope the compiler will share duplicated constants rather than producing a fresh version every time, but it might not too. The repeated text scanning done by the INDEX function for each character of TEXT will of course be a lot slower. A still-more advanced compiler might be able to take advantage of special translation op-codes, on systems that offer them. If storage space is not at a premium a swifter method would be to create something like <code>CHARACTER*1 XLATUC(0:255)</code> with most entries being equal to their index, except for those corresponding to the lower case letters for which the value is the corresponding upper case letter. Then <syntaxhighlight lang="fortran"> DO I = 1,LEN(TEXT)
TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))
TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))
END DO</lang>
END DO</syntaxhighlight>


Note that in EBCDIC the offset is not 32 but 64. Rather than using an undocumented "magic constant" such as 32, one could define <code>PARAMETER (HIC = ICHAR("A") - ICHAR("a"))</code> instead or just place such code in-line and have hope for the compiler. This would also handle the small detail that "A" > "a" in EBCDIC rather than ASCII's "A" < "a". But alas, in EBCDIC the letter codes are ''not'' contiguous (there are many non-letter symbols between "a" and "z" as well as between "A" and "Z"), so the bounds of "A" to "Z" will ''not'' isolate only letters for attack. And it was not just IBM mainframes that used various versions of EBCDIC, so also did Burroughs, among others.
Note that in EBCDIC the offset is not 32 but 64. Rather than using an undocumented "magic constant" such as 32, one could define <code>PARAMETER (HIC = ICHAR("A") - ICHAR("a"))</code> instead or just place such code in-line and have hope for the compiler. This would also handle the small detail that "A" > "a" in EBCDIC rather than ASCII's "A" < "a". But alas, in EBCDIC the letter codes are ''not'' contiguous (there are many non-letter symbols between "a" and "z" as well as between "A" and "Z"), so the bounds of "A" to "Z" will ''not'' isolate only letters for attack. And it was not just IBM mainframes that used various versions of EBCDIC, so also did Burroughs, among others.
Line 1,380: Line 1,863:
Here a complete example, using functions, and as far as I can tell, will work also with EBCDIC:
Here a complete example, using functions, and as far as I can tell, will work also with EBCDIC:


<syntaxhighlight lang="fortran">
<lang Fortran>
module uplow
module uplow
implicit none
implicit none
Line 1,457: Line 1,940:


end program doit
end program doit
</syntaxhighlight>
</lang>

=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64

Dim s As String = "alphaBETA"
Print UCase(s)
Print LCase(s)
Sleep</lang>

{{out}}
<pre>
ALPHABETA
alphabeta
</pre>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
a = "alphaBETA"
a = "alphaBETA"
println[lc[a]]
println[lc[a]]
println[uc[a]]
println[uc[a]]
</syntaxhighlight>
</lang>


These functions use Unicode single- and multiple-character mapping tables and thus try to do the right thing with Unicode, possibly making the string longer in some cases:
These functions use Unicode single- and multiple-character mapping tables and thus try to do the right thing with Unicode, possibly making the string longer in some cases:
<lang frink>uc["Imbiß"] // Last char is \u00df</lang>
<syntaxhighlight lang="frink">uc["Imbiß"] // Last char is \u00df</syntaxhighlight>


Produces:
Produces:
Line 1,488: Line 1,957:
As the Unicode standard for casing states, "it is important to note that no casing operations on strings are reversible:"
As the Unicode standard for casing states, "it is important to note that no casing operations on strings are reversible:"


<lang frink>lc[ uc["Imbiß"] ]</lang>
<syntaxhighlight lang="frink">lc[ uc["Imbiß"] ]</syntaxhighlight>
<pre>imbiss</pre>
<pre>imbiss</pre>


=={{header|FutureBasic}}==
=={{header|GAP}}==
<syntaxhighlight lang="gap">LowercaseString("alphaBETA");
<lang futurebasic>window 1
UppercaseString("alphaBETA");</syntaxhighlight>


=={{header|GDScript}}==
CFStringRef s = @"alphaBETA"
{{works with|Godot|4.0.2}}


<syntaxhighlight lang="gdscript">
print s
extends MainLoop
print ucase(s)
print lcase(s)


HandleEvents</lang>


func _process(_delta: float) -> bool:
Output:
var string: String = "alphaBETA"
<pre>
print(string.to_upper())
alphaBETA
print(string.to_lower())
ALPHABETA
alphabeta
</pre>


# Note: These will also add/remove underscores.
=={{header|Gambas}}==
print("to_camel_case: ", string.to_camel_case())
'''[https://gambas-playground.proko.eu/?gist=d45e91bee011314fd126dc53052b5386 Click this link to run this code]'''
print("to_pascal_case: ", string.to_pascal_case())
<lang gambas>Public Sub Main()
print("to_snake_case: ", string.to_snake_case())
Dim sString As String = "alphaBETA "


return true # Exit
Print UCase(sString)
</syntaxhighlight>
Print LCase(sString)


{{out}}
End</lang>
Output:
<pre>
<pre>
ALPHABETA
ALPHABETA
alphabeta
alphabeta
to_camel_case: alphaBeta
to_pascal_case: AlphaBeta
to_snake_case: alpha_beta
</pre>
</pre>

=={{header|GAP}}==
<lang gap>LowercaseString("alphaBETA");
UppercaseString("alphaBETA");</lang>


=={{header|GML}}==
=={{header|GML}}==
<lang GML>#define cases
<syntaxhighlight lang="gml">#define cases
{
{
x = 'alphaBETA';
x = 'alphaBETA';
Line 1,536: Line 2,001:
show_message(y);
show_message(y);
show_message(z);
show_message(z);
}</lang>
}</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 1,542: Line 2,007:


It is Title() on the other hand, that capitalizes the first letter of each word. It identifies word boundaries and capitalizes first letters, leaving other letters unmodified. As of Go 1.2 though, the word breaking algorithm is not Unicode compliant.
It is Title() on the other hand, that capitalizes the first letter of each word. It identifies word boundaries and capitalizes first letters, leaving other letters unmodified. As of Go 1.2 though, the word breaking algorithm is not Unicode compliant.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,569: Line 2,034:
fmt.Println("Swapping case: ", // DzLjNJ
fmt.Println("Swapping case: ", // DzLjNJ
strings.Map(unicode.SimpleFold, s))
strings.Map(unicode.SimpleFold, s))
}</lang>
}</syntaxhighlight>

Output:
{{out}}

<pre>
<pre>
string: alphaBETA len: 9 runes
string: alphaBETA len: 9 runes
Line 1,599: Line 2,066:
Title words: O'Hare O'HARE O’hare Don'T
Title words: O'Hare O'HARE O’hare Don'T
Swapping case: O'HARE o'hare O’HARE DON'T
Swapping case: O'HARE o'hare O’HARE DON'T
</pre>

Go handles many Unicode characters upcasing well but fails for some like [https://en.wikipedia.org/wiki/%C3%9F ß] where it hasn't changed <code>ß</code> into <code>SS</code> (expected <code>STROSSBÙRRI</code>).

<syntaxhighlight lang="go">
package main

import (
"fmt"
"strings"
)

func main() {
a := "Stroßbùrri"
b := "ĥåçýджк"
fmt.Println(strings.ToUpper(a))
fmt.Println(strings.ToUpper(b))
}
}</syntaxhighlight>

{{out}}

<pre>
STROßBÙRRI
ĤÅÇÝДЖК
</pre>
</pre>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def str = 'alphaBETA'
<syntaxhighlight lang="groovy">def str = 'alphaBETA'


println str.toUpperCase()
println str.toUpperCase()
println str.toLowerCase()</lang>
println str.toLowerCase()</syntaxhighlight>


Output:
Output:
Line 1,612: Line 2,104:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.Char
<syntaxhighlight lang="haskell">import Data.Char


s = "alphaBETA"
s = "alphaBETA"


lower = map toLower s
lower = map toLower s
upper = map toUpper s</lang>
upper = map toUpper s</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>CHARACTER str = "alphaBETA"
<syntaxhighlight lang="hicest">CHARACTER str = "alphaBETA"
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, UpperCase=1) </lang>
EDIT(Text=str, UpperCase=1) </syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
write(map("alphaBETA"))
write(map("alphaBETA"))
write(map("alphaBETA",&lcase,&ucase))
write(map("alphaBETA",&lcase,&ucase))
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
Line 1,639: Line 2,131:
=={{header|J}}==
=={{header|J}}==
Use standard utilities:
Use standard utilities:
<lang j> toupper 'alphaBETA'
<syntaxhighlight lang="j"> toupper 'alphaBETA'
ALPHABETA
ALPHABETA
tolower 'alphaBETA'
tolower 'alphaBETA'
alphabeta</lang>
alphabeta</syntaxhighlight>


or alternative definitions:
or alternative definitions:
<lang j>upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.)
<syntaxhighlight lang="j">upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.)
lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)</lang>
lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)</syntaxhighlight>


For example:
For example:
<lang j> upper 'alphaBETA'
<syntaxhighlight lang="j"> upper 'alphaBETA'
ALPHABETA
ALPHABETA
lower 'alphaBETA'
lower 'alphaBETA'
alphabeta</lang>
alphabeta</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
The ''String'' class offers the ''toUpperCase'' and ''toLowerCase'' methods.
<lang java>String str = "alphaBETA";
There is no title-case, alternate-case, or sentence-case methods.
<syntaxhighlight lang="java">
String string = "alphaBETA".toUpperCase();
</syntaxhighlight>
<syntaxhighlight lang="java">
String string = "alphaBETA".toLowerCase();
</syntaxhighlight>

<br />
Alternately
<syntaxhighlight lang="java">String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println(str.toLowerCase());
//Also works with non-English characters with no modification
//Also works with non-English characters with no modification
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß"</lang>
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß"</syntaxhighlight>


You could also easily create a <tt>swapCase</tt> method using <tt>Character.isLowerCase()</tt>, <tt>Character.isUpperCase()</tt>, and <tt>Character.isLetter()</tt>.
You could also easily create a <tt>swapCase</tt> method using <tt>Character.isLowerCase()</tt>, <tt>Character.isUpperCase()</tt>, and <tt>Character.isLetter()</tt>.


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>alert( "alphaBETA".toUpperCase() );
<syntaxhighlight lang="javascript">alert( "alphaBETA".toUpperCase() );
alert( "alphaBETA".toLowerCase() );</lang>
alert( "alphaBETA".toLowerCase() );</syntaxhighlight>


Output:
Output:
Line 1,673: Line 2,176:


{{works with|NJS| 0.2.5}}
{{works with|NJS| 0.2.5}}
<lang javascript>var string = "alphaBETA";
<syntaxhighlight lang="javascript">var string = "alphaBETA";
var uppercase = string.toUpperCase();
var uppercase = string.toUpperCase();
var lowercase = string.toLowerCase();</lang>
var lowercase = string.toLowerCase();</syntaxhighlight>

=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE
islower == ord 109.5 - abs 13 <;
isupper == ord 77.5 - abs 13 <;
tolower == [[isupper] [32 +] [] ifte] map;
toupper == [[islower] [32 -] [] ifte] map.

"alphaBETA" tolower.
"alphaBETA" toupper.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
'''Works with jq and gojq, the C and Go implementations of jq'''

If your version of jq does not have ascii_downcase and ascii_upcase, then you might want to use their definitions:
If your version of jq does not have ascii_downcase and ascii_upcase, then you might want to use their definitions:
<lang jq># like ruby's downcase - only characters A to Z are affected
<syntaxhighlight lang="jq"># like ruby's downcase - only characters A to Z are affected
def ascii_downcase:
def ascii_downcase:
explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;
explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;
Line 1,685: Line 2,200:
# like ruby's upcase - only characters a to z are affected
# like ruby's upcase - only characters a to z are affected
def ascii_upcase:
def ascii_upcase:
explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;</lang>
explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;
</syntaxhighlight>
jq's regular expression functions have a "case insensitive" option that is often useful
when handling text outside the ASCII range, as is illustrated by the last example below.
Currently, however, there is no built-in case-conversion filter for Unicode characters in general.

'''Examples''':
'''Examples''':
<syntaxhighlight lang="jq">
<lang jq>"alphaBETA" | ascii_upcase
"alphaBETA" | ascii_upcase
#=> "ALPHABETA"
#=> "ALPHABETA"


"alphaBETA" | ascii_downcase
"alphaBETA" | ascii_downcase
#=> "alphabeta"</lang>
#=> "alphabeta"

jq -n '"á" | test("Á";"i")' # case-insensitive search
#=> true
</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>var msg = "alphaBETA";
<syntaxhighlight lang="javascript">var msg = "alphaBETA";
;msg;
;msg;
;msg.toUpperCase();
;msg.toUpperCase();
Line 1,701: Line 2,226:
;msg.toTitle();
;msg.toTitle();
;msg.toLocaleUpperCase();
;msg.toLocaleUpperCase();
;msg.toLocaleLowerCase();</lang>
;msg.toLocaleLowerCase();</syntaxhighlight>


{{out}}
{{out}}
Line 1,713: Line 2,238:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>julia> uppercase("alphaBETA")
<syntaxhighlight lang="julia">julia> uppercase("alphaBETA")
"ALPHABETA"
"ALPHABETA"


julia> lowercase("alphaBETA")
julia> lowercase("alphaBETA")
"alphabeta"</lang>
"alphabeta"</syntaxhighlight>

Some letters like ß (U+00DF) are transformed to ẞ (U+1E9E) in Julia, instead of SS (2 𝗑 U+0053) as expected of the Unicode standard<ref>https://unicode.org/faq/casemap_charprop.html#11</ref>.

<syntaxhighlight lang="julia">
julia> a = 'ß'
'ß': Unicode U+00DF (category Ll: Letter, lowercase)

julia> uppercase(a)
'ẞ': Unicode U+1E9E (category Lu: Letter, uppercase)
</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
{{works with|Kona}}
<lang k>
s:"alphaBETA"
<syntaxhighlight lang="k"> s:"alphaBETA"
upper:{i:_ic x; :[96<i; _ci i-32;_ci i]}'
upper:{i:_ic x; :[96<i; _ci i-32;_ci i]}'
lower:{i:_ic x; :[91>i; _ci i+32;_ci i]}'
lower:{i:_ic x; :[91>i; _ci i+32;_ci i]}' / for reference
upper s
upper s
"ALPHABETA"
"ALPHABETA"
lower s
lower s
"alphabeta"
"alphabeta"
</syntaxhighlight>
</lang>

{{works with|ngn/k}}
<syntaxhighlight lang=K>s:"alphaBETA"
upper: {`c$x+-32*(x>"`")*x<"{"}
lower: {`c$x+32*(x>"@")*x<"["}
lower:_: / built in

upper "This is a test."
"THIS IS A TEST."
lower "This is a test."
"this is a test."
lower s
"alphabeta"
upper s
"ALPHABETA"</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,739: Line 2,289:
println(s.capitalize())
println(s.capitalize())
println(s.decapitalize())
println(s.decapitalize())
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,751: Line 2,301:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Lambdatalk can take benefit from CSS rules.
Lambdatalk can take benefit from CSS rules.
<lang scheme>
<syntaxhighlight lang="scheme">
{span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta
{span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta
{span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA
{span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA
</syntaxhighlight>
</lang>

=={{header|Lang}}==
<syntaxhighlight lang="lang">
$s = alphaBETA
fn.println(fn.toUpper($s))
fn.println(fn.toLower($s))
</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
</pre>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>// Direct string return
<syntaxhighlight lang="lasso">// Direct string return
'alphaBETA'->uppercase&
'alphaBETA'->uppercase&
'alphaBETA'->lowercase&
'alphaBETA'->lowercase&
Line 1,768: Line 2,330:
local(tolower = 'alphaBETA')
local(tolower = 'alphaBETA')
#tolower->lowercase
#tolower->lowercase
#tolower</lang>
#tolower</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
Lingo has no case conversion functions, but for ASCII strings they can e.g. be implemented like this:
Lingo has no case conversion functions, but for ASCII strings they can e.g. be implemented like this:
<lang lingo>----------------------------------------
<syntaxhighlight lang="lingo">----------------------------------------
-- Lower to upper case (ASCII only)
-- Lower to upper case (ASCII only)
-- @param {string} str
-- @param {string} str
Line 1,800: Line 2,362:
end repeat
end repeat
return str
return str
end</lang>
end</syntaxhighlight>


<lang lingo>put toUpper("alphaBETA")
<syntaxhighlight lang="lingo">put toUpper("alphaBETA")
-- "ALPHABETA"
-- "ALPHABETA"


put toLower("alphaBETA")
put toLower("alphaBETA")
-- "alphabeta"</lang>
-- "alphabeta"</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>put upper("alphaBETA") && lower("alphaBETA")
<syntaxhighlight lang="livecode">put upper("alphaBETA") && lower("alphaBETA")
ALPHABETA alphabeta</lang>
ALPHABETA alphabeta</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Line 1,817: Line 2,379:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>str = "alphaBETA"
<syntaxhighlight lang="lua">str = "alphaBETA"

print( string.upper(str) )
print( string.lower(str) )</lang>
print( string.upper(str) ) -- ALPHABETA
print( string.lower(str) ) -- alphabeta

print ( str:upper() ) -- ALPHABETA
print ( str:lower() ) -- alphabeta
</syntaxhighlight>

The [https://www.lua.org/manual/5.4/manual.html#6.4 string library] properly works only for ASCII and extended ASCII (depending on the locals) ranges but not for Unicode.

<syntaxhighlight lang="lua">print ( string.upper("ação") ) -- returns AçãO instead of AÇÃO
print ( string.upper("ĥåçýджк") ) -- returns ĥåçýджк instead of ĤÅÇÝДЖК
</syntaxhighlight>

=={{header|M2000 Interpreter}}==

<syntaxhighlight lang="m2000 interpreter">
Module stringcase {
string s="alphaBETA", s1=s, c="!@@@@<"
print ucase$(s)="ALPHABETA"
print lcase$(s)="alphabeta"
s=str$(s+"ΑΛΦΑ", 1032) ' convert from utf16le to ansi 1032, and enpand to utf16LE as locale 1033
print s="alphaBETAÁËÖÁ"
// trait as utfLE16 but for character code from 0 to 255, and return based on locale 1033
print lcase$(s, 1033)="alphabetaáëöá"
// trait as utfLE16 but for character code from 0 to 255, and return based on locale 1032
print lcase$(s, 1032)="alphabetaαλφα"
print lcase$(s1+"ΑΛΦΑ")="alphabetaαλφα"
print str$(s1, ">")="ALPHABETA"
print str$(s1, "<")="alphabeta"
print str$(s1, c)="beta"
}
stringcase
</syntaxhighlight>
{{out}}
<pre>
True
True
True
True
True
True
True
True
True
</pre>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`upcase', `translit(`$*', `a-z', `A-Z')')
<syntaxhighlight lang="m4">define(`upcase', `translit(`$*', `a-z', `A-Z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')


define(`x',`alphaBETA')
define(`x',`alphaBETA')
upcase(x)
upcase(x)
downcase(x)</lang>
downcase(x)</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>str := "alphaBETA";
<syntaxhighlight lang="maple">str := "alphaBETA";
StringTools:-UpperCase(str);
StringTools:-UpperCase(str);
StringTools:-LowerCase(str);</lang>
StringTools:-LowerCase(str);</syntaxhighlight>
produces
produces
<pre> alphabeta</pre>
<pre> alphabeta</pre>
Line 1,838: Line 2,444:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>str="alphaBETA";
<syntaxhighlight lang="mathematica">str="alphaBETA";
ToUpperCase[str]
ToUpperCase[str]
ToLowerCase[str]</lang>
ToLowerCase[str]</syntaxhighlight>
{{out}}
{{out}}
<pre>ALPHABETA
<pre>ALPHABETA
Line 1,846: Line 2,452:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>>> upper('alphaBETA')
<syntaxhighlight lang="matlab">>> upper('alphaBETA')


ans =
ans =
Line 1,856: Line 2,462:
ans =
ans =


alphabeta</lang>
alphabeta</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang Maxima>supcase('alphaBETA');
<syntaxhighlight lang="maxima">supcase('alphaBETA');
sdowncase('alphaBETA');</lang>
sdowncase('alphaBETA');</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
Requires MAX 2008
Requires MAX 2008
<lang maxscript>str = "alphaBETA"
<syntaxhighlight lang="maxscript">str = "alphaBETA"
print (toUpper str)
print (toUpper str)
print (toLower str)</lang>
print (toLower str)</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
Line 1,872: Line 2,478:
only affect unaccented Latin characters.
only affect unaccented Latin characters.


<lang>:- module string_case.
<syntaxhighlight lang="text">:- module string_case.
:- interface.
:- interface.


Line 1,887: Line 2,493:
io.format("capitalize first: %s\n", [s(capitalize_first(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
% We can use uncaptitalize_first/1 to ensure the first character in a
% string is lower-case.</lang>
% string is lower-case.</syntaxhighlight>


=={{header|Metafont}}==
=={{header|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).
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) =
<syntaxhighlight lang="metafont">vardef isbetween(expr a, i, f) =
if string a:
if string a:
if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)):
if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)):
Line 1,925: Line 2,531:
endfor
endfor
?
?
enddef;</lang>
enddef;</syntaxhighlight>


<lang metafont>message toupper("alphaBETA");
<syntaxhighlight lang="metafont">message toupper("alphaBETA");
message tolower("alphaBETA");
message tolower("alphaBETA");


end</lang>
end</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>"alphaBETA" uppercase
<syntaxhighlight lang="min">"alphaBETA" uppercase
"alphaBETA" lowercase
"alphaBETA" lowercase
"alphaBETA" capitalize</lang>
"alphaBETA" capitalize</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>mixedString = "alphaBETA"
<syntaxhighlight lang="miniscript">mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower</lang>
print "Lower Case of " + mixedString + " is " + mixedString.lower</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,949: Line 2,555:


=={{header|MIPS Assembly}}==
=={{header|MIPS Assembly}}==
This example modifies a string in place. <code>$a0</code> is assumed to contain a pointer to the string ''in RAM,'' writes to ROM will obviously not have the desired effect.
These examples modify a string in place. <code>$a0</code> is assumed to contain a pointer to the string ''in RAM;'' writes to ROM will obviously not have the desired effect.
<syntaxhighlight lang="mips">ToUpper:

<lang mips>ToUpper:
;input: $a0 = pointer to beginning of string
;input: $a0 = pointer to beginning of string
;clobbers: $t0,$t1,$t2
;clobbers: $t0,$t1,$t2
Line 1,959: Line 2,564:
ToUpper_again:
ToUpper_again:


lb $t0,($a0)
lbu $t0,($a0)
nop
nop


beq $t0,ToUpper_done ;if char is null terminator, exit
beqz $t0,ToUpper_done ;if char is null terminator, exit
nop
nop


Line 1,985: Line 2,590:


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToLower:
ToUpper:
;input: $a0 = pointer to beginning of string
;input: $a0 = pointer to beginning of string
;clobbers: $t0,$t1,$t2
;clobbers: $t0,$t1,$t2
Line 1,993: Line 2,598:
ToLower_again:
ToLower_again:


lb $t0,($a0)
lbu $t0,($a0)
nop
nop


beq $t0,ToUpper_done ;not a typo, I did this to save space.
beqz $t0,ToUpper_done ;not a typo, I did this to save space.
nop
nop


Line 2,012: Line 2,617:
addiu $a0,1
addiu $a0,1
b ToLower_again
b ToLower_again
nop</lang>
nop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
li $t1,'A'
li $t2,'Z'
lbu $t0,($a0)
nop
beqz $t0,ToggleCase_done
nop
bltu $t0,$t1,ToggleCase_next
nop
bleu $t0,$t2,ToggleCase_Xor
nop
ToggleCase_next:
addiu $t1,0x20 ;li $t1,'a'
addiu $t2,0x20 ;li $t2,'z'
bltu $t0,$t1,ToggleCase_overhead
nop
bgtu $t0,$t2,ToggleCase_overhead
nop
ToggleCase_Xor:
xori $t0,$t0,0x20
sb $t0,($a0)
ToggleCase_overhead:
addiu $a0,1
b ToggleCase
nop
ToggleCase_done:
jr ra
nop</syntaxhighlight>
{{out}}
<pre>
alphaBETA ;original
ALPHABETA ;uppercase
alphabeta ;lowercase
ALPHAbeta ;toggled</pre>


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
<lang mirc>echo -ag $upper(alphaBETA)
<syntaxhighlight lang="mirc">echo -ag $upper(alphaBETA)
echo -ag $lower(alphaBETA)</lang>
echo -ag $lower(alphaBETA)</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE TextCase EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE TextCase EXPORTS Main;


IMPORT IO, Text, ASCII;
IMPORT IO, Text, ASCII;
Line 2,048: Line 2,692:
IO.Put(Upper("alphaBETA\n"));
IO.Put(Upper("alphaBETA\n"));
IO.Put(Lower("alphaBETA\n"));
IO.Put(Lower("alphaBETA\n"));
END TextCase.</lang>
END TextCase.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,056: Line 2,700:


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
<lang MUMPS>
STRCASE(S)
STRCASE(S)
SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Line 2,064: Line 2,708:
WRITE !,"Lower: "_$TRANSLATE(S,UP,LO)
WRITE !,"Lower: "_$TRANSLATE(S,UP,LO)
QUIT
QUIT
</syntaxhighlight>
</lang>
Output:<pre>
Output:<pre>
USER>DO STRCASE^ROSETTA("alphaBETA")
USER>DO STRCASE^ROSETTA("alphaBETA")
Line 2,074: Line 2,718:


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>string = "alphaBETA"
<syntaxhighlight lang="nanoquery">string = "alphaBETA"


println upper(string)
println upper(string)
println lower(string)</lang>
println lower(string)</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System.Console;
<syntaxhighlight lang="nemerle">using System.Console;
using System.Globalization;
using System.Globalization;


Line 2,094: Line 2,738:


}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols
options replace format comments java crossref savelog symbols
Line 2,106: Line 2,750:
say abc.lower
say abc.lower
say abc.upper(1, 1) -- capitalize 1st character
say abc.upper(1, 1) -- capitalize 1st character
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(upper-case "alphaBETA")
(upper-case "alphaBETA")
(lower-case "alphaBETA")
(lower-case "alphaBETA")
</syntaxhighlight>
</lang>


=={{header|Nial}}==
=={{header|Nial}}==
<lang nial>toupper 'alphaBETA'
<syntaxhighlight lang="nial">toupper 'alphaBETA'
=ALPHABETA
=ALPHABETA
tolower 'alphaBETA'
tolower 'alphaBETA'
=alphabeta</lang>
=alphabeta</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
In the following example, we use the ASCII version of the procedures to convert to lower case, to convert to upper case or to capitalize. In module “unicode” there exists also three procedures "toLower", "toUpper" and "capitalize" which can do the same thing for UTF-8 encoded strings.
In the following example, we use the ASCII version of the procedures to convert to lower case, to convert to upper case or to capitalize. In module “unicode” there exists also three procedures "toLower", "toUpper" and "capitalize" which can do the same thing for UTF-8 encoded strings.


<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


var s: string = "alphaBETA_123"
var s: string = "alphaBETA_123"
Line 2,129: Line 2,773:
echo s, " as lower case: ", toLowerAscii(s)
echo s, " as lower case: ", toLowerAscii(s)
echo s, " as capitalized: ", capitalizeAscii(s)
echo s, " as capitalized: ", capitalizeAscii(s)
echo s, " as normal case: ", normalize(s) # to lower case without underscores.</lang>
echo s, " as normal case: ", normalize(s) # to lower case without underscores.</syntaxhighlight>
{{out}}
{{out}}


Line 2,136: Line 2,780:
alphaBETA_123 as capitalized: AlphaBETA_123
alphaBETA_123 as capitalized: AlphaBETA_123
alphaBETA_123 as normal case: alphabeta123</pre>
alphaBETA_123 as normal case: alphabeta123</pre>

Even with the Unicode specialized procedure, Nim doesn't handle all character correctly. For example, it fails for some characters like [https://en.wikipedia.org/wiki/%C3%9F ß] where it hasn't changed <code>ß</code> into <code>SS</code> (expected <code>STROSSBÙRRI</code>)<ref>https://unicode.org/faq/casemap_charprop.html#11</ref>.

<syntaxhighlight lang="nim">
import unicode
var a: string = "Stroßbùrri"
var b: string = "ĥåçýджк"
echo a.toUpper
echo b.toUpper
</syntaxhighlight>

{{out}}

<pre>
STROßBÙRRI
ĤÅÇÝДЖК
</pre>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
string := "alphaBETA";
string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();
string->ToLower()->PrintLine();
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
{{works with|GNUstep}}
{{works with|GNUstep}}
{{works with|Cocoa}}
{{works with|Cocoa}}
<lang objc>NSLog(@"%@", @"alphaBETA".uppercaseString);
<syntaxhighlight lang="objc">NSLog(@"%@", @"alphaBETA".uppercaseString);
NSLog(@"%@", @"alphaBETA".lowercaseString);
NSLog(@"%@", @"alphaBETA".lowercaseString);


NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"</lang>
NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let str = "alphaBETA" in
let str = "alphaBETA" in
print_endline (String.uppercase_ascii str); (* ALPHABETA *)
print_endline (String.uppercase_ascii str); (* ALPHABETA *)
Line 2,159: Line 2,820:


print_endline (String.capitalize_ascii str); (* AlphaBETA *)
print_endline (String.capitalize_ascii str); (* AlphaBETA *)
;;</lang>
;;</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>s = "alphaBETA";
<syntaxhighlight lang="octave">s = "alphaBETA";
slc = tolower(s);
slc = tolower(s);
suc = toupper(s);
suc = toupper(s);
disp(slc);
disp(slc);
disp(suc);</lang>
disp(suc);</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>"alphaBETA" toUpper
<syntaxhighlight lang="oforth">"alphaBETA" toUpper
"alphaBETA" toLower</lang>
"alphaBETA" toLower</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang Progress (OpenEdge ABL)>caps("alphaBETA")
<syntaxhighlight lang="progress (openedge abl)">caps("alphaBETA")
lc("alphaBETA")
lc("alphaBETA")
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
Convert to upper/lower-case:
Convert to upper/lower-case:
<lang oz>declare
<syntaxhighlight lang="oz">declare
Str = "alphaBETA"
Str = "alphaBETA"
in
in
{System.showInfo {Map Str Char.toUpper}}
{System.showInfo {Map Str Char.toUpper}}
{System.showInfo {Map Str Char.toLower}}</lang>
{System.showInfo {Map Str Char.toLower}}</syntaxhighlight>


Capitalize:
Capitalize:
<lang oz>declare
<syntaxhighlight lang="oz">declare
[StringX] = {Link ['x-oz://system/String.ozf']}
[StringX] = {Link ['x-oz://system/String.ozf']}
in
in
{System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"</lang>
{System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==


<lang pascal>
<syntaxhighlight lang="pascal">
// Uppercase and Lowercase functions for a minimal standard Pascal
// Uppercase and Lowercase functions for a minimal standard Pascal
// where no library routines for these operations exist
// where no library routines for these operations exist
Line 2,260: Line 2,921:
Writeln('Lower case : ',lcase(ab));
Writeln('Lower case : ',lcase(ab));
END.
END.
</syntaxhighlight>
</lang>


Demonstration:
Demonstration:
Line 2,273: Line 2,934:
=={{header|Peloton}}==
=={{header|Peloton}}==
Iterating through the peerset
Iterating through the peerset
<lang sgml><@ ENU$$$LSTPSTLITLIT>UPP|
<syntaxhighlight lang="sgml"><@ ENU$$$LSTPSTLITLIT>UPP|
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@>
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@>
<@ SAY&&&LIT>alphaBETA</@>
<@ SAY&&&LIT>alphaBETA</@>


</@></lang>
</@></syntaxhighlight>


Same code in padded-out, variable-length English dialect
Same code in padded-out, variable-length English dialect
<lang sgml><# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP|
<syntaxhighlight lang="sgml"><# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP|
[<# SAY ELEMENT LIST>...</#>] <# SAY HELP ELEMENT LIST>...</#><# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|...</#>
[<# SAY ELEMENT LIST>...</#>] <# SAY HELP ELEMENT LIST>...</#><# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|...</#>
<# SAY SUPERMACRO LITERAL>alphaBETA</#>
<# SAY SUPERMACRO LITERAL>alphaBETA</#>


</#></lang>
</#></syntaxhighlight>


Output.
Output.
Line 2,306: Line 2,967:
=={{header|Perl}}==
=={{header|Perl}}==
{{works with|Perl|5.x}}
{{works with|Perl|5.x}}
<lang perl>my $string = "alphaBETA";
<syntaxhighlight lang="perl">my $string = "alphaBETA";
print uc($string), "\n"; # => "ALPHABETA"
print uc($string), "\n"; # => "ALPHABETA"
print lc($string), "\n"; # => "alphabeta"
print lc($string), "\n"; # => "alphabeta"
Line 2,312: Line 2,973:


print ucfirst($string), "\n"; # => "AlphaBETA"
print ucfirst($string), "\n"; # => "AlphaBETA"
print lcfirst("FOObar"), "\n"; # => "fOObar"</lang>
print lcfirst("FOObar"), "\n"; # => "fOObar"</syntaxhighlight>


Also works in Perl 4 if the '''my''' is removed.
Also works in Perl 4 if the '''my''' is removed.
Line 2,318: Line 2,979:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"alphaBETA"</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"alphaBETA"</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
There is also a bespoke convertCase function in demo\Edix\Edix.exw which accepts five operators: LOWER, UPPER, CAPITALISE, SENTENCE, and INVERT, which is obviously not part of the language, and a bit too long, messy, ugly, and unedifying, to bother reproducing here.
There is also a bespoke convertCase function in demo\Edix\Edix.exw which accepts five operators: LOWER, UPPER, CAPITALISE, SENTENCE, and INVERT, which is obviously not part of the language, and a bit too long, messy, ugly, and unedifying, to bother reproducing here.


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>$str = "alphaBETA";
<syntaxhighlight lang="php">$str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo strtolower($str), "\n"; // alphabeta
Line 2,333: Line 2,994:
echo lcfirst("FOObar"), "\n"; // fOObar
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz</lang>
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>main =>
<syntaxhighlight lang="picat">main =>
S = "alphaBETA",
S = "alphaBETA",
println(to_uppercase(S)),
println(to_uppercase(S)),
println(to_lowercase(S)).</lang>
println(to_lowercase(S)).</syntaxhighlight>


{{out}}
{{out}}
Line 2,346: Line 3,007:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(let Str "alphaBETA"
<syntaxhighlight lang="picolisp">(let Str "alphaBETA"
(prinl (uppc Str))
(prinl (uppc Str))
(prinl (lowc Str)) )</lang>
(prinl (lowc Str)) )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
Line 2,354: Line 3,015:
output will differ from run to run.
output will differ from run to run.


<lang Pike>string s = "alphaBETA";
<syntaxhighlight lang="pike">string s = "alphaBETA";
string s2 = "foo bar gazonk";
string s2 = "foo bar gazonk";


Line 2,363: Line 3,024:
String.sillycaps(s2),
String.sillycaps(s2),
String.Elite.elite_string(s2));
String.Elite.elite_string(s2));
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,378: Line 3,039:
if sent raw wide strings.
if sent raw wide strings.


<lang Pike>#charset utf8
<syntaxhighlight lang="pike">#charset utf8
void main()
void main()
{
{
Line 2,385: Line 3,046:
s, lower_case(s));
s, lower_case(s));
write( string_to_utf8(out) );
write( string_to_utf8(out) );
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,393: Line 3,054:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>
<syntaxhighlight lang="pli">
declare s character (20) varying initial ('alphaBETA');
declare s character (20) varying initial ('alphaBETA');


put skip list (uppercase(s));
put skip list (uppercase(s));
put skip list (lowercase(s));
put skip list (lowercase(s));
</syntaxhighlight>
</lang>


<lang pli>
<syntaxhighlight lang="pli">
/* An alternative to the above, which might be used if some */
/* An alternative to the above, which might be used if some */
/* non-standard conversion is required, is shown for */
/* non-standard conversion is required, is shown for */
Line 2,406: Line 3,067:
put skip list ( translate(s, 'abcdefghijklmnopqrstuvwxyz',
put skip list ( translate(s, 'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') );
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') );
</syntaxhighlight>
</lang>


=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
<lang plsql>declare
<syntaxhighlight lang="plsql">declare
vc VARCHAR2(40) := 'alphaBETA';
vc VARCHAR2(40) := 'alphaBETA';
ivc VARCHAR2(40);
ivc VARCHAR2(40);
Line 2,418: Line 3,079:
lvc := LOWER(vc); -- 'alphabeta'
lvc := LOWER(vc); -- 'alphabeta'
uvc := UPPER(vc); -- 'ALPHABETA'
uvc := UPPER(vc); -- 'ALPHABETA'
end; </lang>
end; </syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Put "alphaBeta" into a string.
Put "alphaBeta" into a string.
Line 2,431: Line 3,092:
Write the string to the console.
Write the string to the console.
Wait for the escape key.
Wait for the escape key.
Shut down.</lang>
Shut down.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,440: Line 3,101:


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>lvars str = 'alphaBETA';
<syntaxhighlight lang="pop11">lvars str = 'alphaBETA';
lowertoupper(str) =>
lowertoupper(str) =>
uppertolower(str) =></lang>
uppertolower(str) =></syntaxhighlight>


=={{header|Potion}}==
=={{header|Potion}}==
<lang potion>lowercase = (str) :
<syntaxhighlight lang="potion">lowercase = (str) :
low = ("")
low = ("")
str length times (i) :
str length times (i) :
Line 2,469: Line 3,130:


lowercase("alphaBETA") print
lowercase("alphaBETA") print
uppercase("alphaBETA") print</lang>
uppercase("alphaBETA") print</syntaxhighlight>


=={{header|Powerbuilder}}==
=={{header|Powerbuilder}}==
<lang powerbuilder>string ls_string
<syntaxhighlight lang="powerbuilder">string ls_string
ls_string = 'alphaBETA'
ls_string = 'alphaBETA'
ls_string = Upper(ls_string)
ls_string = Upper(ls_string)
ls_string = Lower(ls_string)</lang>
ls_string = Lower(ls_string)</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>
<syntaxhighlight lang="powershell">
$string = 'alphaBETA'
$string = 'alphaBETA'
$lower = $string.ToLower()
$lower = $string.ToLower()
Line 2,485: Line 3,146:


$lower, $upper, $title
$lower, $upper, $title
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,494: Line 3,155:


=={{header|Python}}==
=={{header|Python}}==
<lang python>s = "alphaBETA"
<syntaxhighlight lang="python">s = "alphaBETA"
print s.upper() # => "ALPHABETA"
print s.upper() # => "ALPHABETA"
print s.lower() # => "alphabeta"
print s.lower() # => "alphabeta"
Line 2,504: Line 3,165:


import string
import string
print string.capwords("fOo bAR") # => "Foo Bar"</lang>
print string.capwords("fOo bAR") # => "Foo Bar"</syntaxhighlight>


string.capwords() allows the user to define word separators, and by default behaves slightly differently than title().
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"
<syntaxhighlight lang="python">print "foo's bar".title() # => "Foo'S Bar"
print string.capwords("foo's bar") # => "Foo's Bar"</lang>
print string.capwords("foo's bar") # => "Foo's Bar"</syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==
<lang QB64>DIM s AS STRING * 9
<syntaxhighlight lang="qb64">DIM s AS STRING * 9
s = "alphaBETA"
s = "alphaBETA"
PRINT "The original string: " + s
PRINT "The original string: " + s
PRINT ""
PRINT ""
PRINT "Translated to lowercase: " + LCASE$(s)
PRINT "Translated to lowercase: " + LCASE$(s)
PRINT "Translated to uppercase: " + UCASE$(s)</lang>
PRINT "Translated to uppercase: " + UCASE$(s)</syntaxhighlight>


'''Optimized version:'''
'''Optimized version:'''
Line 2,527: Line 3,188:
* PRINT does not need empty quotes to print a blank line.
* PRINT does not need empty quotes to print a blank line.
* Semi-colons use less data than the concatenation (+) method.
* Semi-colons use less data than the concatenation (+) method.
<lang vb>s$ = "alphaBETA"
<syntaxhighlight lang="vb">s$ = "alphaBETA"
PRINT "The original string: "; s$: PRINT
PRINT "The original string: "; s$: PRINT
PRINT "Converted to lowercase: "; LCASE$(s$)
PRINT "Converted to lowercase: "; LCASE$(s$)
PRINT "Converted to uppercase: "; UCASE$(s$)</lang>
PRINT "Converted to uppercase: "; UCASE$(s$)</syntaxhighlight>




=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ $ "" swap
<syntaxhighlight lang="quackery"> [ $ "" swap
witheach [ upper join ] ] is upper$ ( $ --> $ )
witheach [ upper join ] ] is upper$ ( $ --> $ )


Line 2,543: Line 3,204:
$ "PaTrIcK, I dOn'T tHiNk WuMbO iS a ReAl wOrD."
$ "PaTrIcK, I dOn'T tHiNk WuMbO iS a ReAl wOrD."
dup lower$ echo$ cr
dup lower$ echo$ cr
upper$ echo$ cr</lang>
upper$ echo$ cr</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,552: Line 3,213:


=={{header|R}}==
=={{header|R}}==
<lang R> str <- "alphaBETA"
<syntaxhighlight lang="r"> str <- "alphaBETA"
toupper(str)
toupper(str)
tolower(str)</lang>
tolower(str)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define example "alphaBETA")
(define example "alphaBETA")


Line 2,565: Line 3,226:
;"alphabeta"
;"alphabeta"
(string-titlecase example)
(string-titlecase example)
;"Alphabeta"</lang>
;"Alphabeta"</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,571: Line 3,232:
In Raku, case modification is implemented as builtin subroutine or method:
In Raku, case modification is implemented as builtin subroutine or method:


<lang perl6>my $word = "alpha BETA" ;
<syntaxhighlight lang="raku" line>my $word = "alpha BETA" ;
say uc $word; # all uppercase (subroutine call)
say uc $word; # all uppercase (subroutine call)
say $word.uc; # all uppercase (method call)
say $word.uc; # all uppercase (method call)
Line 2,579: Line 3,240:
say $word.tclc; # first letter titlecase, rest lowercase
say $word.tclc; # first letter titlecase, rest lowercase
say $word.wordcase; # capitalize each word
say $word.wordcase; # capitalize each word
</syntaxhighlight>
</lang>
Output:
Output:
<pre>ALPHA BETA
<pre>ALPHA BETA
Line 2,588: Line 3,249:


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven>'alphaBETA' upper
<syntaxhighlight lang="raven">'alphaBETA' upper
'alhpaBETA' lower</lang>
'alhpaBETA' lower</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>print ["Original: " original: "alphaBETA"]
<syntaxhighlight lang="rebol">print ["Original: " original: "alphaBETA"]
print ["Uppercase:" uppercase original]
print ["Uppercase:" uppercase original]
print ["Lowercase:" lowercase original]</lang>
print ["Lowercase:" lowercase original]</syntaxhighlight>


Output:
Output:
Line 2,603: Line 3,264:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>str: "alphaBETA"
<syntaxhighlight lang="red">str: "alphaBETA"
>> uppercase str
>> uppercase str
== "ALPHABETA"
== "ALPHABETA"
Line 2,609: Line 3,270:
== "alphabeta"
== "alphabeta"
>> uppercase/part str 5
>> uppercase/part str 5
== "ALPHAbeta"</lang>
== "ALPHAbeta"</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>'alphaBETA s:to-upper s:put
<syntaxhighlight lang="retro">'alphaBETA s:to-upper s:put
'alphaBETA s:to-lower s:put</lang>
'alphaBETA s:to-lower s:put</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===with TRANSLATE BIF===
===with TRANSLATE BIF===
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
<lang rexx>abc = "abcdefghijklmnopqrstuvwxyz" /*define all lowercase Latin letters.*/
<syntaxhighlight lang="rexx">abc = "abcdefghijklmnopqrstuvwxyz" /*define all lowercase Latin letters.*/
abcU = translate(abc) /* " " uppercase " " */
abcU = translate(abc) /* " " uppercase " " */


x = 'alphaBETA' /*define a string to a REXX variable. */
x = 'alphaBETA' /*define a string to a REXX variable. */
y = translate(x) /*uppercase X and store it ───► Y */
y = translate(x) /*uppercase X and store it ───► Y */
z = translate(x, abc, abcU) /*translate uppercase──►lowercase chars*/</lang>
z = translate(x, abc, abcU) /*translate uppercase──►lowercase chars*/</syntaxhighlight>


===with PARSE UPPER &amp; PARSE LOWER statements===
===with PARSE UPPER &amp; PARSE LOWER statements===
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
<lang rexx>x = "alphaBETA" /*define a string to a REXX variable. */
<syntaxhighlight lang="rexx">x = "alphaBETA" /*define a string to a REXX variable. */
parse upper var x y /*uppercase X and store it ───► Y */
parse upper var x y /*uppercase X and store it ───► Y */
parse lower var x z /*lowercase X " " " ───► Z */
parse lower var x z /*lowercase X " " " ───► Z */


/*Some REXXes don't support the LOWER option for the PARSE command.*/</lang>
/*Some REXXes don't support the LOWER option for the PARSE command.*/</syntaxhighlight>


===with UPPER &amp; LOWER BIFs===
===with UPPER &amp; LOWER BIFs===
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
<lang rexx>x = 'alphaBETA' /*define a string to a REXX variable. */
<syntaxhighlight lang="rexx">x = 'alphaBETA' /*define a string to a REXX variable. */
y = upper(x) /*uppercase X and store it ───► Y */
y = upper(x) /*uppercase X and store it ───► Y */
z = lower(x) /*lowercase X " " " ───► Z */
z = lower(x) /*lowercase X " " " ───► Z */


/*Some REXXes don't support the UPPER and LOWER BIFs (built-in functions).*/</lang>
/*Some REXXes don't support the UPPER and LOWER BIFs (built-in functions).*/</syntaxhighlight>


===with UPPER statement===
===with UPPER statement===
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
<lang rexx>x = "alphaBETA" /*define a string to a REXX variable. */
<syntaxhighlight lang="rexx">x = "alphaBETA" /*define a string to a REXX variable. */
y=x; upper y /*uppercase X and store it ───► Y */
y=x; upper y /*uppercase X and store it ───► Y */
parse lower var x z /*lowercase Y " " " ───► Z */
parse lower var x z /*lowercase Y " " " ───► Z */


/*Some REXXes don't support the LOWER option for the PARSE command.*/</lang>
/*Some REXXes don't support the LOWER option for the PARSE command.*/</syntaxhighlight>


===with capitalized words===
===with capitalized words===
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
<lang rexx>/*REXX program capitalizes each word in string, and maintains imbedded blanks. */
<syntaxhighlight lang="rexx">/*REXX program capitalizes each word in string, and maintains imbedded blanks. */
x= "alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh",
x= "alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh",
"ayin pe tzadi qof resh shin tav." /*the "old" spelling of Hebrew letters.*/
"ayin pe tzadi qof resh shin tav." /*the "old" spelling of Hebrew letters.*/
Line 2,668: Line 3,329:
end /*j*/
end /*j*/


return substr($, 2) /*return the capitalized words. */</lang>
return substr($, 2) /*return the capitalized words. */</syntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ───► &nbsp; [[CHANGESTR.REX]]. <br>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ───► &nbsp; [[CHANGESTR.REX]]. <br>


Line 2,681: Line 3,342:
===with case swap===
===with case swap===
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
The following code will execute correctly in &nbsp; '''ASCII''' &nbsp; and &nbsp; '''EBCDIC.
<lang rexx>/*REXX program swaps the letter case of a string: lower ──► upper & upper ──► lower.*/
<syntaxhighlight lang="rexx">/*REXX program swaps the letter case of a string: lower ──► upper & upper ──► lower.*/
abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters. */
abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters. */
abcU = translate(abc) /* " " " uppercase " */
abcU = translate(abc) /* " " " uppercase " */
Line 2,689: Line 3,350:
say x
say x
say y
say y
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 2,697: Line 3,358:


===version 2===
===version 2===
<lang rexx>
<syntaxhighlight lang="rexx">
x='alphaBETA'; Say ' x='||x
x='alphaBETA'; Say ' x='||x
Say 'three ways to uppercase'
Say 'three ways to uppercase'
Line 2,709: Line 3,370:
l2=lower(x); Say ' l2='l2
l2=lower(x); Say ' l2='l2
parse lower var x l3; Say ' l3='l3
parse lower var x l3; Say ' l3='l3
</syntaxhighlight>
</lang>
:Note: Parse options upper and lower not available in every Rexx
:Note: Parse options upper and lower not available in every Rexx
:Builtin functions upper and lower not available in every Rexx
:Builtin functions upper and lower not available in every Rexx
Line 2,715: Line 3,376:


For German input (considering umlaute) these will uppercase them:
For German input (considering umlaute) these will uppercase them:
<lang rexx>
<syntaxhighlight lang="rexx">
uppercase: /*courtesy Gerard Schildberger */
uppercase: /*courtesy Gerard Schildberger */
return translate(changestr("ß",translate(arg(1),'ÄÖÜ',"äöü"),'SS'))
return translate(changestr("ß",translate(arg(1),'ÄÖÜ',"äöü"),'SS'))
Line 2,724: Line 3,385:
a=changestr("ß",a,'SS') /* replace ß with SS */
a=changestr("ß",a,'SS') /* replace ß with SS */
return translate(a) /* translate lowercase letters */
return translate(a) /* translate lowercase letters */
</syntaxhighlight>
</lang>
Translation to lowercase is not similarly possible because of 'SS'->'ß' or -> 'ss' ??
Translation to lowercase is not similarly possible because of 'SS'->'ß' or -> 'ss' ??
<br>
<br>
Line 2,730: Line 3,391:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aString = "WELCOME TO THE ring programming language"
aString = "WELCOME TO THE ring programming language"
see lower(aString) + nl
see lower(aString) + nl
see upper(aString) + nl
see upper(aString) + nl
</syntaxhighlight>
</lang>

=={{header|RPL}}==
{{works with|HP|48}}
≪ 1 OVER SIZE '''FOR''' j
DUP j DUP SUB
'''IF''' DUP "a" < OVER "z" > OR '''THEN''' DROP
'''ELSE''' NUM 32 - CHR j SWAP REPL '''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">→UPPER</span>' STO
≪ 1 OVER SIZE '''FOR''' j
DUP j DUP SUB
'''IF''' DUP "A" < OVER "Z" > OR THEN DROP
'''ELSE''' NUM 32 + CHR j SWAP REPL '''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">→LOWER</span>' STO

"alphaBETA" <span style="color:blue">→UPPER</span>
"alphaBETA" <span style="color:blue">→LOWER</span>
{{out}}
<pre>
2: "ALPHABETA"
1: "alphabeta"
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>"alphaBETA".downcase # => "alphabeta"
<syntaxhighlight lang="ruby">"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".upcase # => "ALPHABETA"


"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".capitalize # => "Alphabeta"</lang>
"alphaBETA".capitalize # => "Alphabeta"</syntaxhighlight>


These methods used to affect ASCII letters A-Z and a-z only. From Ruby 2.4 onward however, these methods support Full Unicode case mapping, suitable for most languages, by default. (Options can be specified for Turkic, Lithuanian and ascii)
These methods used to affect ASCII letters A-Z and a-z only. From Ruby 2.4 onward however, these methods support Full Unicode case mapping, suitable for most languages, by default. (Options can be specified for Turkic, Lithuanian and ascii)
{{works with|Ruby| 2.4}}
{{works with|Ruby| 2.4}}
<lang ruby>'ĥåçýджк'.upcase # => "ĤÅÇÝДЖК"</lang>
<syntaxhighlight lang="ruby">'ĥåçýджк'.upcase # => "ĤÅÇÝДЖК"</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{works with|Rust| 1.3}}
{{works with|Rust| 1.3}}
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño
println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>val s="alphaBETA"
<syntaxhighlight lang="scala">val s="alphaBETA"
println(s.toUpperCase) //-> ALPHABETA
println(s.toUpperCase) //-> ALPHABETA
println(s.toLowerCase) //-> alphabeta
println(s.toLowerCase) //-> alphabeta
println(s.capitalize) //-> AlphaBETA
println(s.capitalize) //-> AlphaBETA
println(s.reverse) //-> ATEBahpla</lang>
println(s.reverse) //-> ATEBahpla</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define s "alphaBETA")
<syntaxhighlight lang="scheme">(define s "alphaBETA")
(list->string (map char-upcase (string->list s)))
(list->string (map char-upcase (string->list s)))
(list->string (map char-downcase (string->list s)))</lang>
(list->string (map char-downcase (string->list s)))</syntaxhighlight>


Using SRFI-13:
Using SRFI-13:


<lang scheme>
<syntaxhighlight lang="scheme">
> (define s "alphaBETA gammaDELTA")
> (define s "alphaBETA gammaDELTA")
> (string-upcase s) ;; turn all into upper case
> (string-upcase s) ;; turn all into upper case
Line 2,776: Line 3,461:
> (string-titlecase s) ;; capitalise start of each word
> (string-titlecase s) ;; capitalise start of each word
"Alphabeta Gammadelta"
"Alphabeta Gammadelta"
</syntaxhighlight>
</lang>


=={{header|Sed}}==
=={{header|Sed}}==
Piping through sed in bash:
Piping through sed in bash:


<lang bash>echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
<syntaxhighlight lang="bash">echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'</lang>
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'</syntaxhighlight>


Other functions:
Other functions:
<lang bash># Invert case
<syntaxhighlight lang="bash"># Invert case
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/'</lang>
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/'</syntaxhighlight>


GNU sed supports special sequences to change case:
GNU sed supports special sequences to change case:
<lang bash>
<syntaxhighlight lang="bash">
# to uppercase
# to uppercase
$ echo alphaBETA | sed 's/.*/\U&/'
$ echo alphaBETA | sed 's/.*/\U&/'
Line 2,796: Line 3,481:
$ echo alphaBETA | sed 's/.*/\L&/'
$ echo alphaBETA | sed 's/.*/\L&/'
alphabeta
alphabeta
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 2,803: Line 3,488:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set letters to "alphaBETA"
set letters to "alphaBETA"
put lowercase of letters // alphabeta
put lowercase of letters // alphabeta
Line 2,818: Line 3,503:


put letters //ALPHAbeta
put letters //ALPHAbeta
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>say "alphaBETA".lc; #=> alphabeta
<syntaxhighlight lang="ruby">say "alphaBETA".lc; #=> alphabeta
say "alphaBETA".uc; #=> ALPHABETA
say "alphaBETA".uc; #=> ALPHABETA
say "alphaBETA".tc; #=> AlphaBETA
say "alphaBETA".tc; #=> AlphaBETA
say "alpha BETA".wc; #=> Alpha Beta
say "alpha BETA".wc; #=> Alpha Beta
say "alpha BETA".tc; #=> Alpha BETA
say "alpha BETA".tc; #=> Alpha BETA
say "alpha BETA".tclc; #=> Alpha beta</lang>
say "alpha BETA".tclc; #=> Alpha beta</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang Simula>TEXT soup, lower;
<syntaxhighlight lang="simula">TEXT soup, lower;
soup :- "alphaBETA";
soup :- "alphaBETA";
lower :- LOWCASE(COPY(soup)); ! COPY, else soup is changed;
lower :- LOWCASE(COPY(soup)); ! COPY, else soup is changed;
OutText("upper: "); OutText(UPCASE("alphaBETA"));
OutText("upper: "); OutText(UPCASE("alphaBETA"));
OutText(", lower: "); OutText(lower);
OutText(", lower: "); OutText(lower);
OutText(", soup: "); OutText(soup); Outimage;</lang>
OutText(", soup: "); OutText(soup); Outimage;</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>'alphaBETA' toLowercase.
<syntaxhighlight lang="slate">'alphaBETA' toLowercase.
'alphaBETA' toUppercase.</lang>
'alphaBETA' toUppercase.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>'ALPHAbeta' asUppercase "->'ALPHABETA' "
<syntaxhighlight lang="smalltalk">'ALPHAbeta' asUppercase "->'ALPHABETA' "
'ALPHAbeta' asLowercase "-> 'alphabeta' "</lang>
'ALPHAbeta' asLowercase "-> 'alphabeta' "</syntaxhighlight>
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
{{works with|VisualWorks Smalltalk}}
{{works with|VisualWorks Smalltalk}}
<lang smalltalk>'alphabeta' asUppercaseFirst "-> 'Alphabeta' "</lang>
<syntaxhighlight lang="smalltalk">'alphabeta' asUppercaseFirst "-> 'Alphabeta' "</syntaxhighlight>
Unicode (notice, that this cannot be done simply with a straight forward "ch := ch -$a + $A" loop):
Unicode (notice, that this cannot be done simply with a straight forward "ch := ch -$a + $A" loop):
{{works with|Smalltalk/X}} (may work with other dialects too, but I have not verified)
{{works with|Smalltalk/X}} (may work with other dialects too, but I have not verified)
<lang smalltalk>'αβγω' asUppercase -> 'ΑΒΓΩ'
<syntaxhighlight lang="smalltalk">'αβγω' asUppercase -> 'ΑΒΓΩ'
'ĥåçýджк' asUppercase "-> 'ĤÅÇÝДЖК'
'ĥåçýджк' asUppercase "-> 'ĤÅÇÝДЖК'
'abcäöüáéíýıijńǵȅȇȉ' asUppercase -> 'ABCÄÖÜÁÉÍÝIIJŃǴȄȆȈ'</lang>
'abcäöüáéíýıijńǵȅȇȉ' asUppercase -> 'ABCÄÖÜÁÉÍÝIIJŃǴȄȆȈ'</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 2,856: Line 3,541:
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.
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)
<syntaxhighlight lang="snobol4"> define('uc(str)') :(uc_end)
uc uc = replace(str,&lcase,&ucase) :(return)
uc uc = replace(str,&lcase,&ucase) :(return)
uc_end
uc_end
Line 2,881: Line 3,566:
output = ucfirst(str)
output = ucfirst(str)
output = swapc(str)
output = swapc(str)
end</lang>
end</syntaxhighlight>


An alternative way of constructing the above that groups related functions together in a denser display:
An alternative way of constructing the above that groups related functions together in a denser display:


<lang SNOBOL4> define('UC(STR)')
<syntaxhighlight lang="snobol4"> define('UC(STR)')
define('LC(STR)')
define('LC(STR)')
define('UCFIRST(STR)')
define('UCFIRST(STR)')
Line 2,902: Line 3,587:
output = ucfirst(str)
output = ucfirst(str)
output = swapc(str)
output = swapc(str)
END</lang>
END</syntaxhighlight>


Output:
Output:
Line 2,910: Line 3,595:
AlphaBETA
AlphaBETA
ALPHAbeta</pre>
ALPHAbeta</pre>

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "stringcase" )
@( description, "Take the string 'alphaBETA', and demonstrate how to" )
@( description, "convert it to UPPER-CASE and lower-case. Use the" )
@( description, "default encoding of a string literal or plain ASCII if" )
@( description, "there is no string literal in your language. Show any" )
@( description, "additional case conversion functions (e.g. swapping" )
@( description, "case, capitalizing the first letter, etc.) that may be" )
@( description, "included in the library of your language. " )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/String_case" );
pragma license( unrestricted );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure stringcase is
s : constant string := "alphaBETA";
begin
? strings.to_upper( s );
? strings.to_lower( s );
? strings.to_proper( s );
end stringcase;</syntaxhighlight>


=={{header|SQL}}==
=={{header|SQL}}==
{{works with|MS SQL| 2005}}
{{works with|MS SQL| 2005}}
<lang sql>declare @s varchar(10)
<syntaxhighlight lang="sql">declare @s varchar(10)
set @s = 'alphaBETA'
set @s = 'alphaBETA'
print upper(@s)
print upper(@s)
print lower(@s)</lang>
print lower(@s)</syntaxhighlight>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
With SQL only:
With SQL only:
<lang sql pl>
<syntaxhighlight lang="sql pl">
values upper('alphaBETA');
values upper('alphaBETA');
values lower('alphaBETA');
values lower('alphaBETA');
Line 2,927: Line 3,639:
-- Within a SQL query.
-- Within a SQL query.
select upper('alphaBETA') from sysibm.sysdummy1;
select upper('alphaBETA') from sysibm.sysdummy1;
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,965: Line 3,677:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>val strupr = String.map Char.toUpper;
<syntaxhighlight lang="sml">val strupr = String.map Char.toUpper;
val strlwr = String.map Char.toLower;</lang>
val strlwr = String.map Char.toLower;</syntaxhighlight>


Test
Test
Line 2,979: Line 3,691:
Use '''[https://www.stata.com/help.cgi?f_strupper strupper]''' and '''strlower''' to change case of ASCII characters. Use '''[https://www.stata.com/help.cgi?f_ustrupper ustrupper]''' and '''ustrlower''' to change case of all Unicode letters.
Use '''[https://www.stata.com/help.cgi?f_strupper strupper]''' and '''strlower''' to change case of ASCII characters. Use '''[https://www.stata.com/help.cgi?f_ustrupper ustrupper]''' and '''ustrlower''' to change case of all Unicode letters.


<lang stata>. scalar s="alphaBETA"
<syntaxhighlight lang="stata">. scalar s="alphaBETA"
. di strupper(s)
. di strupper(s)
ALPHABETA
ALPHABETA
. di strlower(s)
. di strlower(s)
alphabeta</lang>
alphabeta</syntaxhighlight>


Notice there may be some difficulties with Unicode characters. In the following, the uppercase '''[https://en.wikipedia.org/wiki/Sigma sigma]''' is correctly converted back to the lowercase variant, but the '''[https://en.wikipedia.org/wiki/Iota_subscript iota subscript]''' is not.
Notice there may be some difficulties with Unicode characters. In the following, the uppercase '''[https://en.wikipedia.org/wiki/Sigma sigma]''' is correctly converted back to the lowercase variant, but the '''[https://en.wikipedia.org/wiki/Iota_subscript iota subscript]''' is not.


<lang stata>. scalar a="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
<syntaxhighlight lang="stata">. scalar a="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. scalar b=ustrupper(a)
. scalar b=ustrupper(a)
. di b
. di b
ἘΝ ἈΡΧΗ͂Ι ἘΠΟΊΗΣΕΝ Ὁ ΘΕῸΣ ΤῸΝ ΟΥ̓ΡΑΝῸΝ ΚΑῚ ΤῊΝ ΓΗ͂Ν
ἘΝ ἈΡΧΗ͂Ι ἘΠΟΊΗΣΕΝ Ὁ ΘΕῸΣ ΤῸΝ ΟΥ̓ΡΑΝῸΝ ΚΑῚ ΤῊΝ ΓΗ͂Ν
. di ustrlower(b)
. di ustrlower(b)
ἐν ἀρχῆι ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν</lang>
ἐν ἀρχῆι ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


println("alphaBETA".uppercaseString)
println("alphaBETA".uppercaseString)
println("alphaBETA".lowercaseString)
println("alphaBETA".lowercaseString)
println("foO BAr".capitalizedString)</lang>
println("foO BAr".capitalizedString)</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 3,008: Line 3,720:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set string alphaBETA
<syntaxhighlight lang="tcl">set string alphaBETA


# three built-in case conversion commands
# three built-in case conversion commands
Line 3,037: Line 3,749:


swapcase Père ;# ==> pÈRE
swapcase Père ;# ==> pÈRE
swapcase_en Père ;# ==> pèRE</lang>
swapcase_en Père ;# ==> pèRE</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
Line 3,055: Line 3,767:


=={{header|Transd}}==
=={{header|Transd}}==
<lang Scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule: {
MainModule: {
Line 3,063: Line 3,775:
(lout (tolower s)))
(lout (tolower s)))
)
)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,071: Line 3,783:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
$$ MODE TUSCRIPT,{}
string="alphaBETA"
string="alphaBETA"
Line 3,080: Line 3,792:
PRINT uppercase1
PRINT uppercase1
PRINT uppercase2
PRINT uppercase2
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,092: Line 3,804:


For System V tr:
For System V tr:
<lang bash>echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA
<syntaxhighlight lang="bash">echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA
echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta</lang>
echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta</syntaxhighlight>


For [[BSD]] tr, [[GNU]] tr, or any [[POSIX]] system:
For [[BSD]] tr, [[GNU]] tr, or any [[POSIX]] system:
<lang bash>echo alphaBETA | tr a-z A-Z # => ALPHABETA
<syntaxhighlight lang="bash">echo alphaBETA | tr a-z A-Z # => ALPHABETA
echo alphaBETA | tr A-Z a-z # => alphabeta</lang>
echo alphaBETA | tr A-Z a-z # => alphabeta</syntaxhighlight>


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.
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.
Line 3,104: Line 3,816:
{{works with|bash}}
{{works with|bash}}


<lang bash>s="alphaBETA"
<syntaxhighlight lang="bash">s="alphaBETA"
echo ${s^^} # => ALPHABETA
echo ${s^^} # => ALPHABETA
echo ${s,,} # => alphabeta
echo ${s,,} # => alphabeta
echo ${s^} # => AlphaBETA</lang>
echo ${s^} # => AlphaBETA</syntaxhighlight>


===Z Shell===
===Z Shell===
{{works with|zsh}}
{{works with|zsh}}


<lang bash>s="alphaBETA"
<syntaxhighlight lang="bash">s="alphaBETA"
echo ${s:u} # => ALPHABETA
echo ${s:u} # => ALPHABETA
echo ${s:l} # => alphabeta</lang>
echo ${s:l} # => alphabeta</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>out (lower "alphaBETA") endl console
<syntaxhighlight lang="ursa">out (lower "alphaBETA") endl console
out (upper "alphaBETA") endl console</lang>
out (upper "alphaBETA") endl console</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Case conversion functions aren't built in but can be defined using the
Case conversion functions aren't built in but can be defined using the
reification operator (-:) to construct a function from a list of pairs.
reification operator (-:) to construct a function from a list of pairs.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std


to_upper = * -:~& ~=`A-~p letters
to_upper = * -:~& ~=`A-~p letters
Line 3,130: Line 3,842:
#show+
#show+


examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'></lang>
examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'></syntaxhighlight>
output:
output:
<pre>ALPHABETA
<pre>ALPHABETA
Line 3,136: Line 3,848:


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>
<syntaxhighlight lang="vala">
string s = "alphaBeta";
string s = "alphaBeta";
// stores ALPHABETA to string
// stores ALPHABETA to string
Line 3,142: Line 3,854:
// stores alphabeta to string
// stores alphabeta to string
string s_lower = s.down();
string s_lower = s.down();
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==
<lang VB>Function StringCase()
<syntaxhighlight lang="vb">Function StringCase()
Dim s As String
Dim s As String
s = "alphaBETA"
s = "alphaBETA"
Line 3,151: Line 3,863:
Debug.Print LCase(s)
Debug.Print LCase(s)
Debug.Print WorksheetFunction.Proper(s)
Debug.Print WorksheetFunction.Proper(s)
End Function</lang>
End Function</syntaxhighlight>


Output:
Output:
Line 3,159: Line 3,871:


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vbscript>Dim MyWord
<syntaxhighlight lang="vbscript">Dim MyWord
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA"
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA") ' Returns "alphabeta"</lang>
MyWord = LCase("alphaBETA") ' Returns "alphabeta"</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>#1 = CP
<syntaxhighlight lang="vedit">#1 = CP
IT("alphaBETA")
IT("alphaBETA")
Case_Upper_Block(#1, CP)
Case_Upper_Block(#1, CP)
Case_Lower_Block(#1, CP)</lang>
Case_Lower_Block(#1, CP)</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|V (Vlang)}}==
{{works with|Visual Basic|VB6 Standard}}
<lang vb>Sub Main()
Const TESTSTRING As String = "alphaBETA"
Debug.Print "initial = " _
& TESTSTRING
Debug.Print "uppercase = " _
& UCase(TESTSTRING)
Debug.Print "lowercase = " _
& LCase(TESTSTRING)
Debug.Print "first letter capitalized = " _
& StrConv(TESTSTRING, vbProperCase)
Debug.Print "length (in characters) = " _
& CStr(Len(TESTSTRING))
Debug.Print "length (in bytes) = " _
& CStr(LenB(TESTSTRING))
Debug.Print "reversed = " _
& StrReverse(TESTSTRING)
Debug.Print "first position of letter A (case-sensitive) = " _
& InStr(1, TESTSTRING, "A", vbBinaryCompare)
Debug.Print "first position of letter A (case-insensitive) = " _
& InStr(1, TESTSTRING, "A", vbTextCompare)
Debug.Print "concatenated with '123' = " _
& TESTSTRING & "123"
End Sub</lang>
{{out}}
<pre>initial = alphaBETA
uppercase = ALPHABETA
lowercase = alphabeta
first letter capitalized = Alphabeta
length (in characters) = 9
length (in bytes) = 18
reversed = ATEBahpla
first position of letter A (case-sensitive) = 9
first position of letter A (case-insensitive) = 1
concatenated with '123' = alphaBETA123</pre>

=={{header|Vlang}}==
{{trans|go}}
{{trans|go}}
<lang vlang>fn show(s string) {
<syntaxhighlight lang="v (vlang)">fn show(s string) {
println('string: $s len: $s.len')
println('string: $s len: $s.len')
println('All upper case: ${s.to_upper()}')
println('All upper case: ${s.to_upper()}')
Line 3,221: Line 3,896:
show('DŽLjnj')
show('DŽLjnj')
show("o'hare O'HARE o’hare don't")
show("o'hare O'HARE o’hare don't")
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 3,247: Line 3,922:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-str}}
{{libheader|Wren-str}}
The 'Str' class supports the following methods:
<lang ecmascript>import "/str" for Str


# ''lower'' - converts all letters to lower case
var s = "alphaBETA"
# ''upper'' - converts all letters to upper case
System.print(Str.upper(s))
# ''capitalize'' - converts only the first letter to upper case
System.print(Str.lower(s))</lang>
# ''title'' - converts the first letter of each word to upper case
# ''swapCase'' - swaps the case of each letter

However, support is limited to letters which have both lower and upper case variants with codepoints < 256. This means that the lower case letters 'ß' and 'ÿ' are never changed by these methods. Although it would be possible to regard 'SS' as the upper case equivalent of 'ß', unfortunately this might not 'round-trip' and would not be compatible with the ''Char.upper'' method in any case. It has not therefore been done.

The 'Utf8' class recently acquired the first four of the above methods though with considerably wider (albeit still incomplete) Unicode coverage. In particular the upper case variants 'ẞ' and 'Ÿ' are now supported - the former was introduced into official German orthography in 2017 (though is optional) and, of course, now round-trips. Title case for 4 supported digraphs is automatically applied by the ''capitalize'' or ''title'' methods when they are the first character of the string (or, word, in the case of the latter).
<syntaxhighlight lang="wren">import "./str" for Str, Utf8

var strs = ["alphaBETA", "ação", "o'hare O'HARE o’hare don't"]
System.print("Using 'Str' class methods:")
for (s in strs) {
System.print(" original : %(s)")
System.print(" lower : %(Str.lower(s))")
System.print(" upper : %(Str.upper(s))")
System.print(" capitalize : %(Str.capitalize(s))")
System.print(" title : %(Str.title(s))")
System.print(" swapCase : %(Str.swapCase(s))")
System.print()
}
var strs2 = ["Stroßbùrri", "ĥåçýджк", "DŽLjnj"]
System.print("Using 'Utf8' class methods:")
for (s in strs2) {
System.print(" original : %(s)")
System.print(" lower : %(Utf8.lower(s))")
System.print(" upper : %(Utf8.upper(s))")
System.print(" capitalize : %(Utf8.capitalize(s))")
System.print(" title : %(Utf8.title(s))")
System.print()
}</syntaxhighlight>


{{out}}
{{out}}
<pre>
<pre>
Using 'Str' class methods:
ALPHABETA
original : alphaBETA
alphabeta
lower : alphabeta
upper : ALPHABETA
capitalize : AlphaBETA
title : AlphaBETA
swapCase : ALPHAbeta

original : ação
lower : ação
upper : AÇÃO
capitalize : Ação
title : Ação
swapCase : AÇÃO

original : o'hare O'HARE o’hare don't
lower : o'hare o'hare o’hare don't
upper : O'HARE O'HARE O’HARE DON'T
capitalize : O'hare O'HARE o’hare don't
title : O'hare O'HARE O’hare Don't
swapCase : O'HARE o'hare O’HARE DON'T

Using 'Utf8' class methods:
original : Stroßbùrri
lower : stroßbùrri
upper : STROẞBÙRRI
capitalize : Stroßbùrri
title : Stroßbùrri

original : ĥåçýджк
lower : ĥåçýджк
upper : ĤÅÇÝДЖК
capitalize : Ĥåçýджк
title : Ĥåçýджк

original : DŽLjnj
lower : džljnj
upper : DŽLJNJ
capitalize : DžLjnj
title : DžLjnj
</pre>
</pre>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \use zero-terminated string convention
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated string convention
include c:\cxpl\stdlib; \ToUpper, ToLower, and 'code' declarations
include c:\cxpl\stdlib; \ToUpper, ToLower, and 'code' declarations


Line 3,277: Line 4,019:
StrToLower(Str);
StrToLower(Str);
Text(0, Str); CrLf(0);
Text(0, Str); CrLf(0);
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 3,288: Line 4,030:
The English alphabet is a subset of the ASCII character set, and the upper and lower case letters are 32 bytes apart. Bit 5 "toggles" the case of any letter in this range. Assuming your string exists in RAM, these subroutines are all that is needed to switch the string from upper to lower case, and vice versa. The first two functions are destructive, meaning that you cannot recover the original string after using them. The <code>ToggleCase</code> function can be performed twice on the same string to get the original string back.
The English alphabet is a subset of the ASCII character set, and the upper and lower case letters are 32 bytes apart. Bit 5 "toggles" the case of any letter in this range. Assuming your string exists in RAM, these subroutines are all that is needed to switch the string from upper to lower case, and vice versa. The first two functions are destructive, meaning that you cannot recover the original string after using them. The <code>ToggleCase</code> function can be performed twice on the same string to get the original string back.


<lang z80>ToUpperCase:
<syntaxhighlight lang="z80">ToUpperCase:
;INPUT:
;INPUT:
;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
Line 3,363: Line 4,105:
pop de
pop de
ret
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;</lang>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;</syntaxhighlight>


{{out}}
{{out}}
Line 3,373: Line 4,115:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>s:="alphaBETA";
<syntaxhighlight lang="zkl">s:="alphaBETA";
s.toLower(); //--> "alphabeta"
s.toLower(); //--> "alphabeta"
s.toUpper(); //--> "ALPHABETA"</lang>
s.toUpper(); //--> "ALPHABETA"</syntaxhighlight>


{{omit from|Openscad}}
{{omit from|Openscad}}
Line 3,381: Line 4,123:


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");


pub fn main() !void {
pub fn main() !void {
Line 3,396: Line 4,138:


// TODO use https://github.com/jecolon/zigstr
// TODO use https://github.com/jecolon/zigstr
}</lang>
}</syntaxhighlight>


=={{header|Zoea}}==
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: uppercase
program: uppercase
input: 'FOObar'
input: 'FOObar'
Line 3,407: Line 4,149:
input: 'FOObar'
input: 'FOObar'
output: 'foobar'
output: 'foobar'
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>

Latest revision as of 14:48, 24 April 2024

Task
String case
You are encouraged to solve this task according to the task description, using any language you may know.
Task

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.

Note: In some languages alphabets toLower and toUpper is not reversable.

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.


Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

Translation of: Python
V s = ‘alphaBETA’
print(s.uppercase())
print(s.lowercase())
Output:
ALPHABETA
alphabeta

360 Assembly

The first version uses a nice thing of EBCDIC coding, uppercase can be performed with a simple 'OR' with blank character (X'40'), in the same way lowercase can be performed with a 'AND' with character 191 (X'BF').

UCASE    CSECT
         USING  UCASE,R15
         MVC    UC,PG
         MVC    LC,PG
         OC     UC,=16C' '         or  X'40' uppercase 
         NC     LC,=16X'BF'        and X'BF' lowercase
         XPRNT  PG,L'PG            print original
         XPRNT  UC,L'UC            print uc
         XPRNT  LC,L'LC            print lc
         BR     R14
PG       DC     CL9'alphaBETA'
UC       DS     CL(L'PG)
LC       DS     CL(L'PG)
         YREGS 
         END    UCASE
Output:
alphaBETA
ALPHABETA
alphabeta

The second version uses the translate operation (TR opcode), but now EBCDIC coding with alphabetic in 3 sequences, makes things a bit longer to create translation tables.

UCASE    CSECT
         USING  UCASE,R15
         MVC    UC,PG
         MVC    LC,PG
         TR     UC,TABLEU          TR uppercase 
         TR     LC,TABLEL          TR lowercase
         XPRNT  PG,L'PG            print original
         XPRNT  UC,L'UC            print uc
         XPRNT  LC,L'LC            print lc
         BR     R14
PG       DC     CL9'alphaBETA'
UC       DS     CL(L'PG)
LC       DS     CL(L'PG)
TABLEU   DC     256AL1(*-TABLEU)
         ORG    TABLEU+C'a'
         DC     C'ABCDEFGHI'
         ORG    TABLEU+C'j'
         DC     C'JKLMNOPQR'
         ORG    TABLEU+C's'
         DC     C'STUVWXYZ'
         ORG
TABLEL   DC     256AL1(*-TABLEL)
         ORG    TABLEL+C'A'
         DC     C'abcdefghi'
         ORG    TABLEL+C'J'
         DC     C'jklmnopqr'
         ORG    TABLEL+C'S'
         DC     C'stuvwxyz'
         ORG
         YREGS 
         END    UCASE
Output:
alphaBETA
ALPHABETA
alphabeta

4D

$string:="alphaBETA"
$uppercase:=Uppercase($string)
$lowercase:=Lowercase($string)

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@_>)]}.

68000 Assembly

These algorithms work for any ASCII string. The implementation of actually printing the characters is left out, as it is not actually relevant to this task.

UpperCase:
;input: A0 = pointer to the string's base address.
;alters the string in-place.

MOVE.B (A0),D0      ;load a letter
BEQ .Terminated     ;we've reached the null terminator.

CMP.B #'a',D0       ;compare to ascii code for a
BCS .overhead       ;if less than a, keep looping.

CMP.B #'z',D0       ;compare to ascii code for z
BHI .overhead       ;if greater than z, keep looping

AND.B #%1101111,D0  ;this "magic constant" turns lower case to upper case, since they're always 32 apart.
.overhead:
MOVE.B D0,(A0)+     ;store the letter back and increment the pointer. 
                    ;If this isn't an alphabetical character, D0 won't change and this store won't affect the string at all.
                    ;If it was a letter, it will have been changed to upper case before storing back.

BRA UpperCase       ;next letter

.Terminated:
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LowerCase:
MOVE.B (A0),D0      ;load a letter
BEQ .Terminated     ;we've reached the null terminator.

CMP.B #'A',D0       ;compare to ascii code for A
BCS .overhead       ;if less than A, keep looping.

CMP.B #'Z',D0       ;compare to ascii code for Z
BHI .overhead      ;if greater than Z, keep looping

OR.B #%00100000,D0  ;this "magic constant" turns upper case to lower case, since they're always 32 apart.
.overhead:
MOVE.B D0,(A0)+     ;store the result and get ready to read the next letter.
BRA LowerCase       ;next letter
.Terminated:
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
MOVE.B (A0),D0     ;load a letter and inc the pointer to the next letter
BEQ .Terminated     ;we've reached the null terminator.

MOVE.B D0,D1        ;copy the letter
AND.B #%11011111    ;convert the copy to upper case so we can check it.

CMP.B #'A',D1       ;compare to ascii code for A
BCS overhead        ;if less than A, keep looping.

CMP.B #'Z',D1       ;compare to ascii code for Z
BHI overhead        ;if greater than Z, keep looping

EOR.B #%00100000,D0 ;swaps the case of the letter
overhead:
MOVE.B D0,(A0)+     ;store the result
BRA ToggleCase      ;next letter
.Terminated:
RTS

8080 Assembly

	org	100h
	jmp	demo
	;;;	Convert CP/M string under [HL] to upper case
unext:	inx	h
ucase:	mov	a,m	; Get character <- entry point is here
	cpi	'$'	; Done?
	rz		; If so, stop
	cpi	'a'	; >= 'a'?
	jc	unext	; If not, next character
	cpi	'z'+1	; <= 'z'?
	jnc	unext	; If not, next character
	sui	32	; Subtract 32
	mov	m,a	; Write character back
	jmp	unext
	;;;	Convert CP/M string under [HL] to lower case
lnext:	inx	h
lcase:	mov	a,m	; Get character <- entry point is here
	cpi	'$'	; Done?
	rz		; If so, stop
	cpi	'A'	; >= 'A'?
	jc	lnext	; If not, next character
	cpi	'Z'+1	; <= 'Z'?
	jnc	lnext	; If not, next character
	adi	32	; Subtract 32
	mov	m,a	; Write character back
	jmp	lnext
	;;;	Apply to given string
demo:	call	print	; Print without change
	lxi	h,str
	call	ucase	; Make uppercase
	call	print	; Print uppercase version
	lxi	h,str
	call	lcase	; Make lowercase (fall through to print)
print:	lxi	d,str	; Print string using CP/M call
	mvi	c,9
	jmp	5
str:	db	'alphaBETA',13,10,'$'
Output:
alphaBETA
ALPHABETA
alphabeta

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
or android 64 bits with application Termux
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program strcase64.s   */

/************************************/
/* Constantes                       */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc" 

/************************************/
/* Initialized data                 */
/************************************/
.data
szMessResult:         .asciz "Result: \n"
szString:             .asciz "alphaBETA"
szCarriageReturn:     .asciz "\n"
szMessStart:          .asciz "Program 64 bits start.\n"
/************************************/
/* UnInitialized data               */
/************************************/
.bss 
sBuffer:            .skip 80
sBuffex1:           .skip 80
/************************************/
/*  code section                    */
/************************************/
.text
.global main 
main:                    // entry of program
    ldr x0,qAdrszMessStart
    bl affichageMess
    ldr x1,qAdrszString
    ldr x3,qAdrsBuffer
    ldr x4,qAdrsBuffex1
    mov x6,#0b100000     // 1 -> bit 5 
    mov x2,#0
1:
    ldrb w0,[x1,x2]      // load byte of string
    mov x5,x0
    cmp x0,#'A'          // select alpha characters lower or upper
    blt 3f
    cmp x0,#'z'
    bgt 3f
    cmp x0,#'Z'
    ble 2f
    cmp x0,#'a'
    bge 2f
    b 3f
2:
    orr x0,x0,x6          // converion in lower case (1 -> bit 5)
    bic x5,x0,x6          // converion in upper case (0 -> bit 5)
3:  
    strb w0,[x3,x2]       // store lower character
    strb w5,[x4,x2]       // store upper character 
    cmp x0,#0             // end string ?
    add x2,x2,#1          // increment index character
    bne 1b                // loop


    ldr x0,qAdrszMessResult
    bl affichageMess
    ldr x0,qAdrsBuffer
    bl affichageMess
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
    ldr x0,qAdrsBuffex1
    bl affichageMess
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
100:                       // standard end of the program
    mov x0, #0             // return code
    mov x8, #EXIT          // request to exit program
    svc 0                  // perform the system call
qAdrszString:             .quad  szString
qAdrsBuffer:              .quad  sBuffer
qAdrsBuffex1:             .quad  sBuffex1
qAdrszMessResult:         .quad  szMessResult
qAdrszCarriageReturn:     .quad  szCarriageReturn
qAdrszMessStart:          .quad  szMessStart
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
Output:
Program 64 bits start.
Result:
alphabeta
ALPHABETA

Action!

INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit

PROC UpperCase(CHAR ARRAY text,res)
  BYTE i

  res(0)=text(0)
  FOR i=1 TO res(0)
  DO
    res(i)=ToUpper(text(i))
  OD
RETURN

PROC LowerCase(CHAR ARRAY text,res)
  BYTE i

  res(0)=text(0)
  FOR i=1 TO res(0)
  DO
    res(i)=ToLower(text(i))
  OD
RETURN

PROC Main()
  CHAR ARRAY text="alphaBETA"
  CHAR ARRAY upper(20),lower(20)

  UpperCase(text,upper)
  LowerCase(text,lower)

  Put(125) PutE() ;clear screen
  PrintF("Original string: ""%S""%E",text)
  PrintF("Upper-case string: ""%S""%E",upper)
  PrintF("Lower-case string: ""%S""%E",lower)
RETURN
Output:

Screenshot from Atari 8-bit computer

Original string: "alphaBETA"
Upper-case string: "ALPHABETA"
Lower-case string: "alphabeta"

ActionScript

var string:String = 'alphaBETA';
var upper:String = string.toUpperCase();
var lower:String = string.toLowerCase();

Ada

with Ada.Characters.Handling, Ada.Text_IO;
use  Ada.Characters.Handling, Ada.Text_IO;

procedure Upper_Case_String is
   S : constant String := "alphaBETA";
begin
   Put_Line (To_Upper (S));
   Put_Line (To_Lower (S));
end Upper_Case_String;

ALGOL 68

Translation of: C – Note: This specimen retains the original C coding style.
Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.
#!/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

ALGOL W

begin
    % algol W doesn't have standard case conversion routines, this is one way %
    % such facilities could be provided                                       %

    % converts text to upper case                                             %
    % assumes the letters are contiguous in the character set (as in ASCII)   %
    % would not work in EBCDIC (as the original algol W implementations used) %
    procedure upCase( string(256) value result text ) ;
        for i := 0 until 255 do begin
            string(1) c;
            c := text( i // 1 );
            if c >= "a" and c <= "z"
            then begin
                text( i // 1 ) := code( decode( "A" )
                                      + ( decode( c ) - decode( "a" ) )
                                      )
            end
        end upCase ;

    % converts text to lower case                                             %
    % assumes the letters are contiguous in the character set (as in ASCII)   %
    % would not work in EBCDIC (as the original algol W implementations used) %
    procedure dnCase( string(256) value result text ) ;
        for i := 0 until 255 do begin
            string(1) c;
            c := text( i // 1 );
            if c >= "A" and c <= "Z"
            then begin
                text( i // 1 ) := code( decode( "a" )
                                      + ( decode( c ) - decode( "A" ) )
                                      )
            end
        end dnCase ;

    string(256) text;
    text := "alphaBETA";
    upCase( text );
    write( text( 0 // 40 ) );
    dnCase( text );
    write( text( 0 // 40 ) );

end.
Output:
ALPHABETA                               
alphabeta                               

Amazing Hopper

#include <hopper.h>

#proto swapcase(_X_)

main:
   
   // literal:
   String to process = "alphaBETA", {"String to process: ",String to process}println
   {"UPPER: ",String to process} upper,println
   {"LOWER: ",String to process} lower,println
   {"SWAP CASE: "}
   s="", let( s := _swap case(String to process)),{s}println
   // arrays:
   vArray=0, {5,5} new array(vArray), vArray=String to process
   {"ARRAY UPPER: \n",vArray} upper,println
   {"ARRAY LOWER: \n",vArray} lower,println
   [1:2:end,1:2:end]get(vArray),upper, put(vArray)
   [2:2:end,2:2:end]get(vArray),lower, put(vArray)
   {"INTERVAL ARRAY UPPER/LOWER: \n",vArray},println
   
exit(0)

.locals
swapcase(_X_)
   nLen=0, {_X_}len,mov(nLen)
   __SWAPCASE__:
      if( [nLen:nLen]get(_X_),{"upper"}!typechar? )
          lower
      else
          upper
      end if
      put(_X_)
      --nLen,{nLen}jnz(__SWAPCASE__)
   {_X_}   // put processed string into the stack...
back
Output:
String to process: alphaBETA
UPPER: ALPHABETA
LOWER: alphabeta
SWAP CASE: ALPHAbeta
ARRAY UPPER: 
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA

ARRAY LOWER: 
alphabeta alphabeta alphabeta alphabeta alphabeta
alphabeta alphabeta alphabeta alphabeta alphabeta
alphabeta alphabeta alphabeta alphabeta alphabeta
alphabeta alphabeta alphabeta alphabeta alphabeta
alphabeta alphabeta alphabeta alphabeta alphabeta

INTERVAL ARRAY UPPER/LOWER: 
ALPHABETA alphaBETA ALPHABETA alphaBETA ALPHABETA
alphaBETA alphabeta alphaBETA alphabeta alphaBETA
ALPHABETA alphaBETA ALPHABETA alphaBETA ALPHABETA
alphaBETA alphabeta alphaBETA alphabeta alphaBETA
ALPHABETA alphaBETA ALPHABETA alphaBETA ALPHABETA

APL

Works with: APL2
      a←'abcdefghijklmnopqrstuvwxyz'
      A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      
      X←'alphaBETA'
      
      (a,⎕AV)[(A,⎕AV)⍳'alphaBETA']
alphabeta
      (A,⎕AV)[(a,⎕AV)⍳'alphaBETA']
ALPHABETA
Works with: APL

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*

APL (Dyalog)

Dyalog APL has a system function for case conversion, ⎕C. This is Unicode-aware and preserves punctuation. If called monadically, maps character arrays to lower case. If called with a left-hand argument of 1, maps character arrays to upper case.

      ⎕C 'Πέτρος is using APL!'
πέτροσ is using apl!
      1 ⎕C 'Πέτρος is using APL!'
ΠΈΤΡΟΣ IS USING APL!

Note: The I-Beam operator with code 819 is now deprecated in favor of the system function ⎕C.

AppleScript

Translation of: JavaScript

AppleScript lacks built in string case functions, but since OS X 10.10 (Yosemite version, Oct 2014) it has been possible to use ObjC Foundation class methods directly in AppleScript code.

use framework "Foundation"

-- TEST -----------------------------------------------------------------------
on run
    
    ap({toLower, toTitle, toUpper}, {"alphaBETA αβγδΕΖΗΘ"})
    
    --> {"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}
    
end run


-- GENERIC FUNCTIONS ----------------------------------------------------------

-- toLower :: String -> String
on toLower(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower

-- toTitle :: String -> String
on toTitle(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toTitle

-- toUpper :: String -> String
on toUpper(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toUpper

-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
    set {nf, nx} to {length of fs, length of xs}
    set lst to {}
    repeat with i from 1 to nf
        tell mReturn(item i of fs)
            repeat with j from 1 to nx
                set end of lst to |λ|(contents of (item j of xs))
            end repeat
        end tell
    end repeat
    return lst
end ap

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}

Arbre

main():
  uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io

Output:

ALPHABETA
alphabeta

ARM Assembly

Works with: as version Raspberry Pi
or android 32 bits with application Termux
/* ARM assembly Raspberry PI  */
/*  program strcase.s   */

/************************************/
/* Constantes                       */
/************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../constantes.inc"

/************************************/
/* Initialized data                 */
/************************************/
.data
szMessResult:         .asciz "Result: \n"
szString:             .asciz "alphaBETA"
szCarriageReturn:     .asciz "\n"
szMessStart:          .asciz "Program 32 bits start.\n"
/************************************/
/* UnInitialized data               */
/************************************/
.bss 
sBuffer:            .skip 80
sBuffer1:           .skip 80
/************************************/
/*  code section                    */
/************************************/
.text
.global main 
main:                    @ entry of program
    ldr r0,iAdrszMessStart
    bl affichageMess
    ldr r1,iAdrszString
    ldr r3,iAdrsBuffer
    ldr r4,iAdrsBuffer1
    mov r6,#0b100000     @ 1 -> bit 5 
    mov r2,#0
1:
    ldrb r0,[r1,r2]      @ load byte of string
    mov r5,r0
    cmp r0,#'A'          @ select alpha characters lower or upper
    blt 3f
    cmp r0,#'z'
    bgt 3f
    cmp r0,#'Z'
    ble 2f
    cmp r0,#'a'
    bge 2f
    b 3f
2:
    orr r0,r0,r6          @ converion in lower case (1 -> bit 5)
    bic r5,r0,r6          @ converion in upper case (0 -> bit 5)
3:  
    strb r0,[r3,r2]       @ store lower character
    strb r5,[r4,r2]       @ store upper character 
    cmp r0,#0             @ end string ?
    add r2,r2,#1          @ increment index character
    bne 1b                @ loop


    ldr r0,iAdrszMessResult
    bl affichageMess
    ldr r0,iAdrsBuffer
    bl affichageMess
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
    ldr r0,iAdrsBuffer1
    bl affichageMess
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
100:                       @ standard end of the program
    mov r0, #0             @ return code
    mov r7, #EXIT          @ request to exit program
    swi 0                  @ perform the system call
iAdrszString:             .int szString
iAdrsBuffer:              .int sBuffer
iAdrsBuffer1:             .int sBuffer1
iAdrszMessResult:         .int szMessResult
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrszMessStart:          .int szMessStart
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
Output:
Program 32 bits start.
Result:
alphabeta
ALPHABETA

Arturo

str: "alphaBETA"

print ["uppercase  :" upper str]
print ["lowercase  :" lower str]
print ["capitalize :" capitalize str]
Output:
uppercase  : ALPHABETA 
lowercase  : alphabeta 
capitalize : AlphaBETA

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"

AutoIt

$sString = "alphaBETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sLowercase = StringLower($sString) ;"alphabeta"

Avail

Print: uppercase "alphaBETA";
Print: lowercase "alphaBETA";

AWK

BEGIN {
  a = "alphaBETA";
  print toupper(a), tolower(a)
}

Capitalize:

BEGIN {
  a = "alphaBETA"; 
  print toupper(substr(a, 1, 1)) tolower(substr(a, 2))
}

BASIC

Works with: QBasic
s$ = "alphaBETA"
PRINT UCASE$(s$)
PRINT LCASE$(s$)

Applesoft BASIC

S$ = "alphaBETA"

UP$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : UP$ = UP$ + CHR$(C - (C > 96 AND C < 123) * 32) : NEXT I : ? UP$

LO$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : LO$ = LO$ + CHR$(C + (C > 64 AND C < 91) * 32) : NEXT I : ? LO$

BASIC256

s$ = "alphaBETA"
print "Original string: "; s$
print "To Lower case:   "; lower(s$)
print "To Upper case:   "; upper(s$)

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

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
10 s$ = "alphaBETA"
20 print "Original string: ";s$
30 print "To Lower case:   ";lcase$(s$)
40 print "To Upper case:   ";ucase$(s$)

Commodore BASIC

The example here is based on AppleSoft BASIC, however, Commodore machines have a slightly different interpretation of ASCII:

  • On a number of Commodore machines, the default character set at startup is uppercase letters with graphic symbols. In this instance, standard ASCII codes apply, which means printing the result of ASC("A") returns 65, and printing the result of ASC("♠") (SHIFT-A) returns 193. (Not 97... More on this below.)
  • However, on many of these Commodore machines, the character mode can be changed(†) to an alternate set of glyphs which consists of lowercase letters as well as uppercase letters. When this happens, the former uppercase letter glyphs are replaced with lowercase letter glyphs, and the graphics glyphs are replaced with uppercase letter glyphs. This maintains intuitive use of the computer where typing an uppercase letter is accomplished by holding the SHIFT key while pressing the letter, but the downside is that now the equivalent ASCII codes are reversed: 65 equates to a lowercase "a" (should be 97), and 97 equates to an uppercase "A".
  • In addition to all of this, characters 192 through 255 are duplicates of other characters in the lower realms of the table. This allows one to easily use bit 7 as a flag for a shifted character. This is perhaps one reason why BASIC's ASC returns values for shifted letters starting at 193. In any case, it needs to be accounted for, and actually makes this task simpler.


† Exceptions to the above would be early PET 2001 models that either had no lowercase letters at all, or had upper and lowercase, but were locked into traditional ASCII encoding. The code example will not behave as expected on these models.

It should be noted that the program starts by sending a control code 14 to the display immediately after clearing the screen, which ensures that the computer is displaying the mixed lowercase/uppercase character set, otherwise the output will be a mix of uppercase letters and graphics.

Code Example

10 rem string case                      
15 rem rosetta code                     
20 s$="alphaBETA"                       
30 print chr$(147);chr$(14)             
40 print "The original string is:"      
41 print:print tab(11);s$               
50 up$="":lo$=""                        
55 for i=1 to len(s$)                   
60 c=asc(mid$(s$,i,1))                  
65 up$=up$+chr$(c or 128)               
70 lo$=lo$+chr$(c and 127)              
75 next i                               
80 print:print "Uppercase: ";up$        
90 print "Lowercase: ";lo$
Output:
The original string is:                 
                                        
           alphaBETA                    
                                        
Uppercase: ALPHABETA                    
Lowercase: alphabeta                    
                                        
ready.                                  
█

FreeBASIC

' FB 1.05.0 Win64

Dim s As String = "alphaBETA" 
Print UCase(s)
Print LCase(s)
Sleep
Output:
ALPHABETA
alphabeta

FutureBasic

window 1

CFStringRef s = @"alphaBETA"

print s
print ucase(s)
print lcase(s)

HandleEvents

Output:

alphaBETA
ALPHABETA
alphabeta

Gambas

Click this link to run this code

Public Sub Main()
Dim sString As String = "alphaBETA "

Print UCase(sString)
Print LCase(sString)

End

Output:

ALPHABETA 
alphabeta

IS-BASIC

100 INPUT PROMPT "String:     ":TX$
110 PRINT "Lower case: ";LCASE$(TX$)
120 PRINT "Upper case: ";UCASE$(TX$)

Liberty BASIC

Works with: Just BASIC
Works with: Run BASIC
input$ ="alphaBETA"

print input$
print upper$( input$)
print lower$( input$)

end

PureBasic

s$ = "alphaBETA"
upper$ = UCase(s$)  ;uppercase
lower$ = LCase(s$)  ;lowercase

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case:   "; LCASE$(s$)
PRINT "To Upper case:   "; UCASE$(s$)

Run BASIC

Works with: Just BASIC
Works with: Liberty BASIC
a$ ="alphaBETA"
 
print a$           '=> alphaBETA
print upper$(a$)   '=> ALPHABETA
print lower$(a$)   '=> alphabeta

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.

True BASIC

LET s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case:   "; LCASE$(s$)
PRINT "To Upper case:   "; UCASE$(s$)
END

Visual Basic

Works with: Visual Basic version VB6 Standard
Sub Main()
Const TESTSTRING As String = "alphaBETA"
Debug.Print "initial   =                                      " _
   & TESTSTRING
Debug.Print "uppercase =                                      " _
   & UCase(TESTSTRING)
Debug.Print "lowercase =                                      " _
   & LCase(TESTSTRING)
Debug.Print "first letter capitalized =                       " _
   & StrConv(TESTSTRING, vbProperCase)
Debug.Print "length (in characters) =                         " _
   & CStr(Len(TESTSTRING))
Debug.Print "length (in bytes) =                              " _
   & CStr(LenB(TESTSTRING))
Debug.Print "reversed =                                       " _
   & StrReverse(TESTSTRING)
Debug.Print "first position of letter A (case-sensitive) =    " _
   & InStr(1, TESTSTRING, "A", vbBinaryCompare)
Debug.Print "first position of letter A (case-insensitive) =  " _
   & InStr(1, TESTSTRING, "A", vbTextCompare)
Debug.Print "concatenated with '123' =                        " _
   & TESTSTRING & "123"
End Sub
Output:
initial   =                                      alphaBETA
uppercase =                                      ALPHABETA
lowercase =                                      alphabeta
first letter capitalized =                       Alphabeta
length (in characters) =                         9
length (in bytes) =                              18
reversed =                                       ATEBahpla
first position of letter A (case-sensitive) =    9
first position of letter A (case-insensitive) =  1
concatenated with '123' =                        alphaBETA123

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()
:"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

XBasic

Works with: Windows XBasic
PROGRAM	"StringCase"
VERSION	"0.0000"

DECLARE FUNCTION  Entry ()

FUNCTION  Entry ()
s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case:   "; LCASE$(s$)
PRINT "To Upper case:   "; UCASE$(s$)

END FUNCTION
END PROGRAM

Yabasic

s$ = "alphaBETA"
print "Original string: ", s$
print "To Lower case:   ", lower$(s$)
print "To Upper case:   ", upper$(s$)

BCPL

get "libhdr"

// Check whether a character is an upper or lowercase letter
let islower(x) = 'a' <= x <= 'z'
let isupper(x) = 'A' <= x <= 'Z'

// Convert a character to upper or lowercase
let toupper(x) = islower(x) -> x - 32, x
let tolower(x) = isupper(x) -> x + 32, x

// Map a character function over a string
let strmap(f,s) = valof
$(  for i=1 to s%0 do s%i := f(s%i)
    resultis s
$)

// Convert a string to upper or lowercase
let strtoupper(s) = strmap(toupper,s)
let strtolower(s) = strmap(tolower,s)

let start() be
$(  let s = "alphaBETA"
    writef("   String: %S*N", s)
    writef("Uppercase: %S*N", strtoupper(s))
    writef("Lowercase: %S*N", strtolower(s))
$)
Output:
   String: alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta


Beef

using System;

namespace StringCase
{
  class Program
  {
    public static void Main()
    {
      String input = scope .("alphaBETA");
      input.ToUpper();
      Console.WriteLine(input);
      input.ToLower();
      Console.WriteLine(input);
    }
  }
}
Output:
ALPHABETA
alphabeta

Befunge

Works with: befungee

Converts to uppercase only; lowercase is done in a similar way so I chose not to add it.

"ATEBahpla" > : #v_ 25* , @         >48*-v
                 > :: "`"` \"{"\` * |    > , v
                                    >    ^
            ^                                <

BQN

Both idioms are from BQNcrate. For reference, in both examples performs a binary search to check if the characters are in the respective alphabet range. Based on that, the correct number is added at those locations to change case.

Upr  -(32×1="a{")	# Uppercase ASCII text
Lwr  +(32×1="A[")	# Lowercase ASCII text
   str ← "alphaBETA"
"alphaBETA"
   Upr str
"ALPHABETA"
   Lwr str
"alphabeta"

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

Burlesque

blsq ) "alphaBETA"^^zz\/ZZ
"ALPHABETA"
"alphabeta"

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;
}

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"));

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;
}

Clojure

(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string))

CMake

string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}")
-- Uppercase: ALPHABETA
-- Lowercase: alphabeta

COBOL

Standard-compliant Methods

       IDENTIFICATION DIVISION.
       PROGRAM-ID. string-case-85.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  example PIC X(9) VALUE "alphaBETA".

       01  result  PIC X(9).

       PROCEDURE DIVISION.
           DISPLAY "Example: " example

           *> Using the intrinsic functions.
           DISPLAY "Lower-case: " FUNCTION LOWER-CASE(example)

           DISPLAY "Upper-case: " FUNCTION UPPER-CASE(example)

           *> Using INSPECT
           MOVE example TO result
           INSPECT result CONVERTING "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
               TO "abcdefghijklmnopqrstuvwxyz"
           DISPLAY "Lower-case: " result

           MOVE example TO result
           INSPECT result CONVERTING "abcdefghijklmnopqrstuvwxyz"
               TO  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
           DISPLAY "Upper-case: " result

           GOBACK
           .

Compiler Extensions

       IDENTIFICATION DIVISION.
       PROGRAM-ID. string-case-extensions.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       78  example VALUE "alphaBETA".

       01  result  PIC X(9).

       PROCEDURE DIVISION.
           DISPLAY "Example: " example

           *> ACUCOBOL-GT
           MOVE example TO result
           CALL "C$TOLOWER" USING result, BY VALUE 9
           DISPLAY "Lower-case: " result

           MOVE example TO result
           CALL "C$TOUPPER" USING result, BY VALUE 9
           DISPLAY "Upper-case: " result

           *> Visual COBOL
           MOVE example TO result
           CALL "CBL_TOLOWER" USING result, BY VALUE 9
           DISPLAY "Lower-case: " result

           MOVE example TO result
           CALL "CBL_TOUPPER" USING result BY VALUE 9
           DISPLAY "Upper-case: " result

           GOBACK
           .

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)>

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"

Component Pascal

BlackBox Component Builder

MODULE AlphaBeta;
IMPORT StdLog,Strings;

PROCEDURE Do*;
VAR
	str,res: ARRAY 128 OF CHAR;
BEGIN
	str := "alphaBETA";
	Strings.ToUpper(str,res);
	StdLog.String("Uppercase:> ");StdLog.String(res);StdLog.Ln;
	Strings.ToLower(str,res);
	StdLog.String("Lowercase:> ");StdLog.String(res);StdLog.Ln
END Do;

END AlphaBeta.

Execute: ^Q AlphaBeta.Do
Output:

Uppercase:> ALPHABETA
Lowercase:> alphabeta

Crystal

"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"

"alphaBETA".capitalize # => "Alphabeta"

Fully works with all Unicode range.

"ĥåçýджк".upcase  # => "ĤÅÇÝДЖК"

D

void main() {
    import std.stdio, std.string;

    immutable s = "alphaBETA";
    s.toUpper.writeln;
    s.toLower.writeln;
}
Output:
ALPHABETA
alphabeta

Dart

String capitalize(String string) {
  if (string.isEmpty) {
    return string;
  }
  return string[0].toUpperCase() + string.substring(1);
}

void main() {
  var s = 'alphaBETA';
  print('Original string: $s');
  print('To Lower case:   ${s.toLowerCase()}');
  print('To Upper case:   ${s.toUpperCase()}');
  print('To Capitalize:   ${capitalize(s)}');
}
Output:
Original string: alphaBETA
To Lower case:   alphabeta
To Upper case:   ALPHABETA
To Capitalize:   AlphaBETA

DBL

OPEN (1,O,'TT:')              ;open video

STR="alphaBETA"

LOCASE STR
DISPLAY (1,STR,10)            ;alphabeta

UPCASE STR
DISPLAY (1,STR,10)            ;ALPHABETA

Delphi

writeln(uppercase('alphaBETA'));
writeln(lowercase('alphaBETA'));

DWScript

PrintLn(UpperCase('alphaBETA'));
PrintLn(LowerCase('alphaBETA'));

Dyalect

let str = "alphaBETA"
 
print("Lower case: ", str.Lower(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Capitalize: ", str.Capitalize(), separator: "")

E

["alphaBETA".toUpperCase(),
"alphaBETA".toLowerCase()]

EasyLang

EasyLang does not have string case functions. The functions provided below only work with ASCII.

func$ toUpper s$ .
   for c$ in strchars s$
      code = strcode c$
      if code >= 97 and code <= 122
         code -= 32
      .
      res$ &= strchar code
   .
   return res$
.
func$ toLower s$ .
   for c$ in strchars s$
      code = strcode c$
      if code >= 65 and code <= 90
         code += 32
      .
      res$ &= strchar code
   .
   return res$
.
string$ = "alphaBETA"
print string$
print toUpper string$
print toLower string$
Output:
alphaBETA
ALPHABETA
alphabeta

EchoLisp

EchoLisp includes the usual case conversion functions and the randcase function : random case

(string-downcase "alphaBETA")
     "alphabeta"
(string-upcase "alphaBETA")
     "ALPHABETA"
(string-titlecase "alphaBETA")
     "Alphabeta"
(string-randcase "alphaBETA")
     "alphaBEtA"
(string-randcase "alphaBETA")
     "AlPHaBeTA"

ECL

IMPORT STD; //Imports the Standard Library

STRING MyBaseString := 'alphaBETA';

UpperCased := STD.str.toUpperCase(MyBaseString);
LowerCased := STD.str.ToLowerCase(MyBaseString);
TitleCased := STD.str.ToTitleCase(MyBaseString);

OUTPUT (UpperCased);
OUTPUT (LowerCased);
OUTPUT (TitleCased);

Ecstasy

The methods on String are toUppercase() and toLowercase():

module test {
    void run() {
        @Inject Console console;
        console.print($"{"alphaBETA".toLowercase()=}");
        console.print($"{"alphaBETA".toUppercase()=}");
    }
}
Output:
x$ xec test
"alphaBETA".toLowercase()=alphabeta
"alphaBETA".toUppercase()=ALPHABETA

Elena

ELENA 6.x:

import system'culture;
 
public program()
{
    string s1 := "alphaBETA";
 
    console.writeLine(s1.toLower(currentLocale));
    console.writeLine(s1.toUpper(currentLocale));
    console.readChar()
}

Elixir

The String module provides the following functions:

String.downcase("alphaBETA")
# => alphabeta
String.upcase("alphaBETA")
# => ALPHABETA
String.capitalize("alphaBETA")
# => Alphabeta

As with most String functions in Elixir, these are fully compatible with Unicode.

String.downcase("αΒ")
# => αβ
String.upcase("αΒ")
# => ΑΒ
String.capitalize("αΒ")
# => Αβ
String.upcase("ß")
# => SS

Elm

import String exposing (toLower, toUpper)

s = "alphaBETA"
 
lower = toLower s
upper = toUpper s

EMal

var samples = text["alphaBETA", "ação", "o'hare O'HARE o’hare don't", "Stroßbùrri", "ĥåçýджк", "DŽLjnj"]
for each var sample in samples
  writeLine("  original   : " + sample)
  writeLine("  lower      : " + sample.lower())
  writeLine("  upper      : " + sample.upper())
  writeLine()
end
Output:
  original   : alphaBETA
  lower      : alphabeta
  upper      : ALPHABETA

  original   : ação
  lower      : ação
  upper      : AÇÃO

  original   : o'hare O'HARE o’hare don't
  lower      : o'hare o'hare o’hare don't
  upper      : O'HARE O'HARE O’HARE DON'T

  original   : Stroßbùrri
  lower      : stroßbùrri
  upper      : STROßBÙRRI

  original   : ĥåçýджк
  lower      : ĥåçýджк
  upper      : ĤÅÇÝДЖК

  original   : DŽLjnj
  lower      : džljnj
  upper      : DŽLJNJ

Erlang

string:to_upper("alphaBETA").
string:to_lower("alphaBETA").

Excel

Take 3 cells, say A1,B1 and C1. In B1 type :

=LOWER(A1)

and in C1 :

=UPPER(A1)

For the stated input in A1, the result will be :

alphaBETA	alphabeta	ALPHABETA

F#

let s = "alphaBETA"
let upper = s.ToUpper()
let lower = s.ToLower()

Factor

"alphaBETA" >lower  ! "alphabeta"
"alphaBETA" >upper  ! "ALPHABETA"
"alphaBETA" >title  ! "Alphabeta"
"ß" >case-fold      ! "ss"

Falcon

printl("alphaBETA".lower())
printl("alphaBETA".upper())

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

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

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

Functions could be used instead, especially with later compilers that enable lengths not fixed at compile time, but this involves copying the text about. By contrast, the subroutines alter the text in-place, though if something like Utext = Uppercase(text) is desired so that both versions are available, a subroutine is less convenient.

F90 introduced the intrinsic function i = IACHAR(c), which returns the integer value of the position of character c in the ASCII character set, even if the processor's default character set is different, such as perhaps EBCDIC. Function ACHAR is the inverse. If the bit pattern of the character was not being interpreted as in the ASCII set, this will cause odd results, say on a system using EBCDIC or (on an ASCII-using cpu) for a file originating from an EBCDIC-using system. Some systems offer additional options to the file OPEN statement that enable character conversion between ASCII and EBCDIC, and there may also be options concerning big- and little-endian usage. But much will depend on the format of the data in the file. If the data are a mixture of text, integers, floating-point, etc. all in binary, there will be no hope for such simple translations.

For converting lower-case text to upper, the following will work both on an ASCII system and an EBCDIC system (or any other encodement), once it is compiled for that system:

      SUBROUTINE UPCASE(TEXT)
       CHARACTER*(*) TEXT
       INTEGER I,C
        DO I = 1,LEN(TEXT)
          C = INDEX("abcdefghijklmnopqrstuvwxyz",TEXT(I:I))
          IF (C.GT.0) TEXT(I:I) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"(C:C)
        END DO
      END

The INDEX function of course returning zero if the character is not found. Converting from upper to lower case is the obvious inverse and it might be worthwhile defining a MODULE with suitable named character constants to avoid repetition - one might hope the compiler will share duplicated constants rather than producing a fresh version every time, but it might not too. The repeated text scanning done by the INDEX function for each character of TEXT will of course be a lot slower. A still-more advanced compiler might be able to take advantage of special translation op-codes, on systems that offer them. If storage space is not at a premium a swifter method would be to create something like CHARACTER*1 XLATUC(0:255) with most entries being equal to their index, except for those corresponding to the lower case letters for which the value is the corresponding upper case letter. Then

      DO I = 1,LEN(TEXT)
        TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))
      END DO

Note that in EBCDIC the offset is not 32 but 64. Rather than using an undocumented "magic constant" such as 32, one could define PARAMETER (HIC = ICHAR("A") - ICHAR("a")) instead or just place such code in-line and have hope for the compiler. This would also handle the small detail that "A" > "a" in EBCDIC rather than ASCII's "A" < "a". But alas, in EBCDIC the letter codes are not contiguous (there are many non-letter symbols between "a" and "z" as well as between "A" and "Z"), so the bounds of "A" to "Z" will not isolate only letters for attack. And it was not just IBM mainframes that used various versions of EBCDIC, so also did Burroughs, among others.

Here a complete example, using functions, and as far as I can tell, will work also with EBCDIC:

module uplow
   implicit none
   character(len=26), parameter, private :: low  = "abcdefghijklmnopqrstuvwxyz"
   character(len=26), parameter, private :: high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
contains

   function to_upper(s) result(t)
      ! returns upper case of s
      implicit none
      character(len=*), intent(in) :: s
      character(len=len(s))        :: t

      character(len=1), save       :: convtable(0:255)
      logical, save                :: first = .true.
      integer                      :: i

      if(first) then
         do i=0,255
            convtable(i) = char(i)
         enddo
         do i=1,len(low)
            convtable(iachar(low(i:i))) = char(iachar(high(i:i)))
         enddo
         first = .false.
      endif

      t = s

      do i=1,len_trim(s)
         t(i:i) = convtable(iachar(s(i:i)))
      enddo

   end function to_upper

   function to_lower(s) result(t)
      ! returns lower case of s
      implicit none
      character(len=*), intent(in) :: s
      character(len=len(s))        :: t

      character(len=1), save :: convtable(0:255)
      logical, save          :: first = .true.
      integer                :: i

      if(first) then
         do i=0,255
            convtable(i) = char(i)
         enddo
         do i = 1,len(low)
            convtable(iachar(high(i:i))) = char(iachar(low(i:i)))
         enddo
         first = .false.
      endif

      t = s

      do i=1,len_trim(s)
         t(i:i) = convtable(iachar(s(i:i)))
      enddo

   end function to_lower


end module uplow


program doit
   use uplow
   character(len=40) :: s

   s = "abcdxyz ZXYDCBA _!@"
   print *,"original: ",'[',s,']'
   print *,"to_upper: ",'[',to_upper(s),']'
   print *,"to_lower: ",'[',to_lower(s),']'

end program doit

Frink

a = "alphaBETA"
println[lc[a]]
println[uc[a]]

These functions use Unicode single- and multiple-character mapping tables and thus try to do the right thing with Unicode, possibly making the string longer in some cases:

uc["Imbiß"] // Last char is \u00df

Produces:

IMBISS

As the Unicode standard for casing states, "it is important to note that no casing operations on strings are reversible:"

lc[ uc["Imbiß"] ]
imbiss

GAP

LowercaseString("alphaBETA");
UppercaseString("alphaBETA");

GDScript

Works with: Godot version 4.0.2
extends MainLoop


func _process(_delta: float) -> bool:
	var string: String = "alphaBETA"
	print(string.to_upper())
	print(string.to_lower())

	# Note: These will also add/remove underscores.
	print("to_camel_case: ", string.to_camel_case())
	print("to_pascal_case: ", string.to_pascal_case())
	print("to_snake_case: ", string.to_snake_case())

	return true # Exit
Output:
ALPHABETA
alphabeta
to_camel_case: alphaBeta
to_pascal_case: AlphaBeta
to_snake_case: alpha_beta

GML

#define cases
{
    x = 'alphaBETA';
    y = string_upper(x); // returns ALPHABETA
    z = string_lower(x); // returns alphabeta
    show_message(y);
    show_message(z);
}

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. ToTitle() converts a string to all title case.

It is Title() on the other hand, that capitalizes the first letter of each word. It identifies word boundaries and capitalizes first letters, leaving other letters unmodified. As of Go 1.2 though, the word breaking algorithm is not Unicode compliant.

package main

import (
    "fmt"
    "strings"
    "unicode"
    "unicode/utf8"
)

func main() {
    show("alphaBETA")
    show("alpha BETA")
    // Three digraphs that should render similar to DZ, Lj, and nj.
    show("DŽLjnj")
    // Unicode apostrophe in third word.
    show("o'hare O'HARE o’hare don't")
}

func show(s string) {
    fmt.Println("\nstring:         ",
        s, " len:", utf8.RuneCountInString(s), "runes") // DZLjnj
    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
    fmt.Println("Title words:    ", strings.Title(s))   // Dzljnj
    fmt.Println("Swapping case:  ",                     // DzLjNJ
        strings.Map(unicode.SimpleFold, s))
}
Output:
string:          alphaBETA  len: 9 runes
All upper case:  ALPHABETA
All lower case:  alphabeta
All title case:  ALPHABETA
Title words:     AlphaBETA
Swapping case:   ALPHAbeta

string:          alpha BETA  len: 10 runes
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 runes
All upper case:  DŽLJNJ
All lower case:  džljnj
All title case:  DžLjNj
Title words:     DžLjnj
Swapping case:   DžljNJ

string:          o'hare O'HARE o’hare don't  len: 26 runes
All upper case:  O'HARE O'HARE O’HARE DON'T
All lower case:  o'hare o'hare o’hare don't
All title case:  O'HARE O'HARE O’HARE DON'T
Title words:     O'Hare O'HARE O’hare Don'T
Swapping case:   O'HARE o'hare O’HARE DON'T

Go handles many Unicode characters upcasing well but fails for some like ß where it hasn't changed ß into SS (expected STROSSBÙRRI).

package main

import (
  "fmt"
  "strings"
)

func main() {
  a := "Stroßbùrri"
  b := "ĥåçýджк"
  fmt.Println(strings.ToUpper(a))
  fmt.Println(strings.ToUpper(b))
}
}
Output:
STROßBÙRRI
ĤÅÇÝДЖК

Groovy

def str = 'alphaBETA'

println str.toUpperCase()
println str.toLowerCase()

Output:

ALPHABETA
alphabeta

Haskell

import Data.Char

s = "alphaBETA"

lower = map toLower s
upper = map toUpper s

HicEst

CHARACTER str = "alphaBETA"
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, UpperCase=1)

Icon and Unicon

procedure main()
    write(map("alphaBETA"))
    write(map("alphaBETA",&lcase,&ucase))
end

IDL

str = "alphaBETA"
print, str
print, strupcase(str) 
print, strlowcase(str)

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

Java

The String class offers the toUpperCase and toLowerCase methods. There is no title-case, alternate-case, or sentence-case methods.

String string = "alphaBETA".toUpperCase();
String string = "alphaBETA".toLowerCase();


Alternately

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().

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();

Joy

DEFINE
  islower == ord 109.5 - abs 13 <;
  isupper == ord 77.5 - abs 13 <;
  tolower == [[isupper] [32 +] [] ifte] map;
  toupper == [[islower] [32 -] [] ifte] map.

"alphaBETA" tolower.
"alphaBETA" toupper.

jq

Works with jq and gojq, the C and Go implementations of jq

If your version of jq does not have ascii_downcase and ascii_upcase, then you might want to use their definitions:

# like ruby's downcase - only characters A to Z are affected
def ascii_downcase:
  explode | map( if 65 <= . and . <= 90 then . + 32  else . end) | implode;

# like ruby's upcase - only characters a to z are affected
def ascii_upcase:
  explode | map( if 97 <= . and . <= 122 then . - 32  else . end) | implode;

jq's regular expression functions have a "case insensitive" option that is often useful when handling text outside the ASCII range, as is illustrated by the last example below. Currently, however, there is no built-in case-conversion filter for Unicode characters in general.

Examples:

"alphaBETA" | ascii_upcase
#=> "ALPHABETA"

"alphaBETA" | ascii_downcase
#=> "alphabeta"

jq -n '"á" | test("Á";"i")' # case-insensitive search 
#=> true

Jsish

var msg = "alphaBETA";
;msg;
;msg.toUpperCase();
;msg.toLowerCase();

;msg.toTitle();
;msg.toLocaleUpperCase();
;msg.toLocaleLowerCase();
Output:
prompt$ jsish --U string-case.jsi
msg ==> alphaBETA
msg.toUpperCase() ==> ALPHABETA
msg.toLowerCase() ==> alphabeta
msg.toTitle() ==> Alphabeta
msg.toLocaleUpperCase() ==> ALPHABETA
msg.toLocaleLowerCase() ==> alphabeta

Julia

julia> uppercase("alphaBETA")
"ALPHABETA"

julia> lowercase("alphaBETA")
"alphabeta"

Some letters like ß (U+00DF) are transformed to ẞ (U+1E9E) in Julia, instead of SS (2 𝗑 U+0053) as expected of the Unicode standard[1].

julia> a = 'ß'
'ß': Unicode U+00DF (category Ll: Letter, lowercase)

julia> uppercase(a)
'ẞ': Unicode U+1E9E (category Lu: Letter, uppercase)

K

Works with: Kona
  s:"alphaBETA"
  upper:{i:_ic x; :[96<i; _ci i-32;_ci i]}'
  lower:{i:_ic x; :[91>i; _ci i+32;_ci i]}' / for reference
  upper s
"ALPHABETA"
  lower s
"alphabeta"
Works with: ngn/k
s:"alphaBETA"
upper: {`c$x+-32*(x>"`")*x<"{"}
lower: {`c$x+32*(x>"@")*x<"["}
lower:_: / built in

upper "This is a test."
"THIS IS A TEST."
lower "This is a test."
"this is a test."
lower s
"alphabeta"
upper s
"ALPHABETA"

Kotlin

// version 1.0.6

fun main(args: Array<String>) {
    val s = "alphaBETA"
    println(s.toUpperCase())
    println(s.toLowerCase()) 
    println(s.capitalize())
    println(s.decapitalize())    
}
Output:
ALPHABETA
alphabeta
AlphaBETA
alphaBETA

Lambdatalk

Lambdatalk can take benefit from CSS rules.

{span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta
{span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA

Lang

$s = alphaBETA
fn.println(fn.toUpper($s))
fn.println(fn.toLower($s))
Output:
ALPHABETA
alphabeta

Lasso

// Direct string return
'alphaBETA'->uppercase&
'alphaBETA'->lowercase&

// Assignment and manipulation of variables
local(toupper = 'alphaBETA')
#toupper->uppercase
#toupper

local(tolower = 'alphaBETA')
#tolower->lowercase
#tolower

Lingo

Lingo has no case conversion functions, but for ASCII strings they can e.g. be implemented like this:

----------------------------------------
-- Lower to upper case (ASCII only)
-- @param {string} str
-- @return {string}
----------------------------------------
on toUpper (str)
  alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  len = str.length
  repeat with i = 1 to len
    pos = offset(str.char[i], alphabet)
    if pos > 0 then put alphabet.char[pos] into char i of str
  end repeat
  return str
end

----------------------------------------
-- Upper to lower case (ASCII only)
-- @param {string} str
-- @return {string}
----------------------------------------
on toLower (str)
  alphabet = "abcdefghijklmnopqrstuvwxyz"
  len = str.length
  repeat with i = 1 to len
    pos = offset(str.char[i], alphabet)
    if pos > 0 then put alphabet.char[pos] into char i of str
  end repeat
  return str
end
put toUpper("alphaBETA")
-- "ALPHABETA"

put toLower("alphaBETA")
-- "alphabeta"

LiveCode

put upper("alphaBETA") && lower("alphaBETA")
ALPHABETA alphabeta

print uppercase "alphaBETA  ; ALPHABETA
print lowercase "alphaBETA  ; alphabeta

Lua

str = "alphaBETA"

print( string.upper(str) ) -- ALPHABETA
print( string.lower(str) ) -- alphabeta

print ( str:upper() ) -- ALPHABETA
print ( str:lower() ) -- alphabeta

The string library properly works only for ASCII and extended ASCII (depending on the locals) ranges but not for Unicode.

print ( string.upper("ação") ) -- returns AçãO instead of AÇÃO
print ( string.upper("ĥåçýджк") ) -- returns ĥåçýджк instead of ĤÅÇÝДЖК

M2000 Interpreter

Module stringcase {
	string s="alphaBETA", s1=s, c="!@@@@<"
	print ucase$(s)="ALPHABETA"
	print lcase$(s)="alphabeta"
	s=str$(s+"ΑΛΦΑ", 1032) ' convert from utf16le to ansi 1032, and enpand to utf16LE as locale 1033
	print s="alphaBETAÁËÖÁ"
	// trait as utfLE16 but for character code from 0 to 255, and return based on locale 1033
	print lcase$(s, 1033)="alphabetaáëöá"
	// trait as utfLE16 but for character code from 0 to 255, and return based on locale 1032
	print lcase$(s, 1032)="alphabetaαλφα"
	print lcase$(s1+"ΑΛΦΑ")="alphabetaαλφα"
	print str$(s1, ">")="ALPHABETA"
	print str$(s1, "<")="alphabeta"
	print str$(s1, c)="beta"
}
stringcase
Output:
   True
   True
   True
   True
   True
   True
   True
   True
   True

M4

define(`upcase', `translit(`$*', `a-z', `A-Z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')

define(`x',`alphaBETA')
upcase(x)
downcase(x)

Maple

str := "alphaBETA";
StringTools:-UpperCase(str);
StringTools:-LowerCase(str);

produces

     alphabeta
     ALPHABETA

Mathematica/Wolfram Language

str="alphaBETA";
ToUpperCase[str]
ToLowerCase[str]
Output:
ALPHABETA
alphabeta

MATLAB / Octave

>> upper('alphaBETA')

ans =

ALPHABETA

>> lower('alphaBETA')

ans =

alphabeta

Maxima

supcase('alphaBETA');
sdowncase('alphaBETA');

MAXScript

Requires MAX 2008

str = "alphaBETA"
print (toUpper str)
print (toLower str)

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.

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

min

Works with: min version 0.19.3
"alphaBETA" uppercase
"alphaBETA" lowercase
"alphaBETA" capitalize

MiniScript

mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower
Output:
Upper Case of alphaBETA is ALPHABETA
Lower Case of alphaBETA is alphabeta

MIPS Assembly

These examples modify a string in place. $a0 is assumed to contain a pointer to the string in RAM; writes to ROM will obviously not have the desired effect.

ToUpper:
;input: $a0 = pointer to beginning of string
;clobbers: $t0,$t1,$t2

	li $t1,'a'
	li $t2,'z'
ToUpper_again:

	lbu $t0,($a0)
	nop

	beqz $t0,ToUpper_done     ;if char is null terminator, exit
	nop

	bltu $t0,$t1,ToUpper_overhead    ;if char stored in $t0 < 'a', skip
	nop

	bgtu $t0,$t2,ToUpper_overhead    ;if char stored in $t0 > 'z', skip
	nop


	andi $t0,$t0,0xDF        ;otherwise, do the work.
	sb $t0,($a0)

ToUpper_overhead:
	addiu $a0,1
	b ToUpper_again
	nop

ToUpper_done:
	jr ra
	nop

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToLower:
	;input: $a0 = pointer to beginning of string
	;clobbers: $t0,$t1,$t2

	li $t1,'A'
	li $t2,'Z'
ToLower_again:

	lbu $t0,($a0)
	nop

	beqz $t0,ToUpper_done     		;not a typo, I did this to save space.
	nop

	bltu $t0,$t1,ToLower_overhead    ;if char stored in $t0 < 'a', skip
	nop

	bgtu $t0,$t2,ToLower_overhead    ;if char stored in $t0 > 'z', skip
	nop


	ori $t0,$t0,0x20
	sb $t0,($a0)

ToLower_overhead:
	addiu $a0,1
	b ToLower_again
	nop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
	li $t1,'A'
	li $t2,'Z'
	
	lbu $t0,($a0)
	nop
	
	beqz $t0,ToggleCase_done
	nop
	
	bltu $t0,$t1,ToggleCase_next
	nop
	bleu $t0,$t2,ToggleCase_Xor
	nop
ToggleCase_next:
	addiu $t1,0x20	;li $t1,'a'
	addiu $t2,0x20	;li $t2,'z'
	
	bltu $t0,$t1,ToggleCase_overhead
	nop
	bgtu $t0,$t2,ToggleCase_overhead
	nop
ToggleCase_Xor:
	xori $t0,$t0,0x20
	sb $t0,($a0)
ToggleCase_overhead:
	addiu $a0,1
	b ToggleCase
	nop
ToggleCase_done:
	jr ra
	nop
Output:
alphaBETA  ;original
ALPHABETA  ;uppercase
alphabeta  ;lowercase
ALPHAbeta  ;toggled

mIRC Scripting Language

echo -ag $upper(alphaBETA)
echo -ag $lower(alphaBETA)

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

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

Output:

USER>DO STRCASE^ROSETTA("alphaBETA")
 
Given: alphaBETA
Upper: ALPHABETA
Lower: alphabeta

Nanoquery

string = "alphaBETA"

println upper(string)
println lower(string)

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"));

    }
}

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

NewLISP

(upper-case "alphaBETA")
(lower-case "alphaBETA")

Nial

toupper 'alphaBETA'
=ALPHABETA
tolower 'alphaBETA'
=alphabeta

Nim

In the following example, we use the ASCII version of the procedures to convert to lower case, to convert to upper case or to capitalize. In module “unicode” there exists also three procedures "toLower", "toUpper" and "capitalize" which can do the same thing for UTF-8 encoded strings.

import strutils

var s: string = "alphaBETA_123"
echo s, " as upper case: ", toUpperAscii(s)
echo s, " as lower case: ", toLowerAscii(s)
echo s, " as capitalized: ", capitalizeAscii(s)
echo s, " as normal case: ", normalize(s)  # to lower case without underscores.
Output:
alphaBETA_123 as upper case: ALPHABETA_123
alphaBETA_123 as lower case: alphabeta_123
alphaBETA_123 as capitalized: AlphaBETA_123
alphaBETA_123 as normal case: alphabeta123

Even with the Unicode specialized procedure, Nim doesn't handle all character correctly. For example, it fails for some characters like ß where it hasn't changed ß into SS (expected STROSSBÙRRI)[2].

import unicode
var a: string = "Stroßbùrri"
var b: string = "ĥåçýджк"
echo a.toUpper
echo b.toUpper
Output:
STROßBÙRRI
ĤÅÇÝДЖК

Objeck

string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();

Objective-C

Works with: GNUstep
Works with: Cocoa
NSLog(@"%@", @"alphaBETA".uppercaseString);
NSLog(@"%@", @"alphaBETA".lowercaseString);

NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"

OCaml

let () =
  let str = "alphaBETA" in
  print_endline (String.uppercase_ascii str); (* ALPHABETA *)
  print_endline (String.lowercase_ascii str); (* alphabeta *)

  print_endline (String.capitalize_ascii str); (* AlphaBETA *)
;;

Octave

s = "alphaBETA";
slc = tolower(s);
suc = toupper(s);
disp(slc);
disp(suc);

Oforth

"alphaBETA" toUpper
"alphaBETA" toLower

OpenEdge/Progress

caps("alphaBETA") 
lc("alphaBETA")

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"

Pascal

// Uppercase and Lowercase functions for a minimal standard Pascal
// where no library routines for these operations exist
PROGRAM upperlower;

// convert a character to uppercase
FUNCTION uch(ch: CHAR): CHAR;
	BEGIN
		uch := ch;
		IF ch IN ['a'..'z'] THEN
			uch := chr(ord(ch) AND $5F);
	END;
	
// convert a character to lowercase
FUNCTION lch(ch: CHAR): CHAR;
	BEGIN
		lch := ch;
		IF ch IN ['A'..'Z'] THEN
			lch := chr(ord(ch) OR $20);
	END;
	
// toggle uper/lower case character
FUNCTION ulch(ch: CHAR): CHAR;
	BEGIN
		ulch := ch;
		IF ch IN ['a'..'z'] THEN ulch := uch(ch);
		IF ch IN ['A'..'Z'] THEN ulch := lch(ch);
	END;
	
// convert a string to uppercase
FUNCTION ucase(str: STRING): STRING;
	var i: Integer;
	BEGIN
		ucase := '';
		FOR i := 1 TO Length(str) DO
			ucase := ucase + uch(str[i]);
	END;
	
// convert a string to lowercase
FUNCTION lcase(str: STRING): STRING;
	var i: Integer;
	BEGIN
		lcase := '';
		FOR i := 1 TO Length(str) DO
			lcase := lcase + lch(str[i]);
	END;

// reverse cases in a given string
FUNCTION ulcase(str: STRING): STRING;
	var i: Integer;
	BEGIN
		ulcase := '';
		FOR i := 1 TO Length(str) DO
			ulcase := ulcase + ulch(str[i]);
	END;

VAR
	ab : STRING = 'alphaBETA';
	
BEGIN
	// demonstration
	Writeln('Original string : ',ab);
	Writeln('Reversed case   : ',ulcase(ab));
	Writeln('Upper case      : ',ucase(ab));
	Writeln('Lower case      : ',lcase(ab));
END.

Demonstration:

Original string : alphaBETA
Reversed case   : ALPHAbeta
Upper case      : ALPHABETA
Lower case      : alphabeta

Peloton

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

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.

Phix

Library: Phix/basics
constant s = "alphaBETA"
?upper(s)
?lower(s)

There is also a bespoke convertCase function in demo\Edix\Edix.exw which accepts five operators: LOWER, UPPER, CAPITALISE, SENTENCE, and INVERT, which is obviously not part of the language, and a bit too long, messy, ugly, and unedifying, to bother reproducing here.

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

Picat

main =>
   S = "alphaBETA",
   println(to_uppercase(S)),
   println(to_lowercase(S)).
Output:
ALPHABETA
alphabeta

PicoLisp

(let Str "alphaBETA"
   (prinl (uppc Str))
   (prinl (lowc Str)) )

Pike

Note: String.Elite.elite_string has an element of randomness, so the output will differ from run to run.

string s = "alphaBETA";
string s2 = "foo bar gazonk";

write("Upper: %O\nLower: %O\nCapitalize: %O\nSilly: %O\nElite: %O\n",
      upper_case(s),
      lower_case(s),
      String.capitalize(s),
      String.sillycaps(s2),
      String.Elite.elite_string(s2));
Output:
Upper: "ALPHABETA"
Lower: "alphabeta"
Capitalize: "AlphaBETA"
Silly: "Foo Bar Gazonk"
Elite: "fo() 8ar 6azo|\\||<"

When dealing with Unicode (or any other supported encoding) care must be taken primarily in the output step to serialize the Unicode string into something the sink can handle. IO functions will throw an error if sent raw wide strings.

#charset utf8
void main()
{
    string s = upper_case("ἀρχῇ ß");
    string out = sprintf("Upper: %s\nLower: %s\n",
			 s, lower_case(s));
    write( string_to_utf8(out) );
}
Output:
Upper: ἈΡΧῇ ß
Lower: ἀρχῇ ß

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') );

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;

Plain English

To run:
Start up.
Put "alphaBeta" into a string.
Uppercase the string.
Write the string to the console.
Lowercase the string.
Write the string to the console.
Capitalize the string.
Write the string to the console.
Wait for the escape key.
Shut down.
Output:
ALPHABETA
alphabeta
Alphabeta

Pop11

lvars str = 'alphaBETA';
lowertoupper(str) =>
uppertolower(str) =>

Potion

lowercase = (str) :
   low = ("")
   str length times (i) :
      low append(if (65 <= str(i) ord and str(i) ord <= 90) :
         "abcdefghijklmnopqrstuvwxyz"(str(i) ord - 65)
      . else :
         str(i)
      .)
   .
   low join("")
.
uppercase = (str) :
   upp = ("")
   str length times (i) :
      upp append(if (97 <= str(i) ord and str(i) ord <= 122) :
         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"(str(i) ord - 97)
      . else :
         str(i)
      .)
   .
   upp join("")
.

lowercase("alphaBETA") print
uppercase("alphaBETA") print

Powerbuilder

string ls_string
ls_string = 'alphaBETA'
ls_string  = Upper(ls_string)
ls_string  = Lower(ls_string)

PowerShell

$string = 'alphaBETA'
$lower  = $string.ToLower()
$upper  = $string.ToUpper()
$title  = (Get-Culture).TextInfo.ToTitleCase($string)

$lower, $upper, $title
Output:
alphabeta
ALPHABETA
Alphabeta

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"

QB64

DIM s AS STRING * 9
s = "alphaBETA"
PRINT "The original string: " + s
PRINT ""
PRINT "Translated to lowercase: " + LCASE$(s)
PRINT "Translated to uppercase: " + UCASE$(s)

Optimized version:
CBTJD: 2020/03/13


  • String does not have to be defined with a specific length using DIM.
  • Addding the string identifier ($) to the variable is sufficient.
  • PRINT does not need empty quotes to print a blank line.
  • Semi-colons use less data than the concatenation (+) method.
s$ = "alphaBETA"
PRINT "The original string: "; s$: PRINT
PRINT "Converted to lowercase: "; LCASE$(s$)
PRINT "Converted to uppercase: "; UCASE$(s$)


Quackery

  [ $ "" swap 
    witheach [ upper join ] ] is upper$ ( $ --> $ )

  [ $ "" swap 
    witheach [ lower join ] ] is lower$ ( $ --> $ )

   $ "PaTrIcK, I dOn'T tHiNk WuMbO iS a ReAl wOrD."
   dup lower$ echo$ cr
       upper$ echo$ cr
Output:
patrick, i don't think wumbo is a real word.
PATRICK, I DON'T THINK WUMBO IS A REAL WORD.


R

 str <- "alphaBETA"
 toupper(str)
 tolower(str)

Racket

#lang racket
(define example "alphaBETA")

(string-upcase example)
;"ALPHABETA"
(string-downcase example)
;"alphabeta"
(string-titlecase example)
;"Alphabeta"

Raku

(formerly Perl 6) In Raku, 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.wordcase;   # capitalize each word

Output:

ALPHA BETA
alpha beta
Alpha BETA
Alpha beta
Alpha Beta

Raven

'alphaBETA' upper
'alhpaBETA' lower

REBOL

print ["Original: " original: "alphaBETA"]
print ["Uppercase:" uppercase original]
print ["Lowercase:" lowercase original]

Output:

Original:  alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta

Red

str: "alphaBETA"
>> uppercase str
== "ALPHABETA"
>> lowercase str
== "alphabeta"
>> uppercase/part str 5
== "ALPHAbeta"

Retro

'alphaBETA s:to-upper s:put
'alphaBETA s:to-lower s:put

REXX

with TRANSLATE BIF

The following code will execute correctly in   ASCII   and   EBCDIC.

abc  = "abcdefghijklmnopqrstuvwxyz"              /*define all  lowercase  Latin letters.*/
abcU = translate(abc)                            /*   "    "   uppercase    "      "    */

x = 'alphaBETA'                                  /*define a string to a REXX variable.  */
y = translate(x)                                 /*uppercase  X  and store it ───►  Y   */
z = translate(x, abc, abcU)                      /*translate uppercase──►lowercase chars*/

with PARSE UPPER & PARSE LOWER statements

The following code will execute correctly in   ASCII   and   EBCDIC.

x = "alphaBETA"                                  /*define a 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.*/

with UPPER & LOWER BIFs

The following code will execute correctly in   ASCII   and   EBCDIC.

x = 'alphaBETA'                                  /*define a 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).*/

with UPPER statement

The following code will execute correctly in   ASCII   and   EBCDIC.

x = "alphaBETA"                                  /*define a 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.*/

with capitalized words

The following code will execute correctly in   ASCII   and   EBCDIC.

/*REXX program  capitalizes  each word in string, and 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."           /*the "old" spelling of Hebrew letters.*/
y= capitalize(x)                                 /*capitalize each word in the string.  */
say x                                            /*display the original string of words.*/
say y                                            /*   "     "    capitalized      words.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
capitalize: procedure;  parse arg z;   $=' 'z    /*prefix    $    string with a  blank. */
            abc = "abcdefghijklmnopqrstuvwxyz"   /*define all  Latin  lowercase letters.*/

                      do j=1  for 26             /*process each letter in the alphabet. */
                      _=' 'substr(abc,j,1); _U=_ /*get a  lowercase  (Latin) letter.    */
                      upper _U                   /* "  "  uppercase     "       "       */
                      $=changestr(_, $, _U)      /*maybe capitalize some word(s).       */
                      end   /*j*/

            return substr($, 2)                  /*return the capitalized words.        */

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.

with case swap

The following code will execute correctly in   ASCII   and   EBCDIC.

/*REXX program  swaps the letter case of a string:  lower ──► upper  &  upper ──► lower.*/
abc = "abcdefghijklmnopqrstuvwxyz"               /*define all the  lowercase  letters.  */
abcU = translate(abc)                            /*   "    "   "   uppercase     "      */

x = 'alphaBETA'                                  /*define a string to a REXX variable.  */
y = translate(x,  abc || abcU,  abcU || abc)     /*swap case of  X  and store it ───► Y */
say x
say y
                                                 /*stick a fork in it,  we're all done. */

output

alphaBETA
ALPHAbeta

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' ??
Note: Recently an uppercase ß was introduced in Austria. I haven't used it yet.

Ring

aString = "WELCOME TO THE ring programming language"
see lower(aString) + nl
see upper(aString) + nl

RPL

Works with: HP version 48
≪ 1 OVER SIZE FOR j 
     DUP j DUP SUB
     IF DUP "a" < OVER "z" > OR THEN DROP
     ELSE NUM 32 - CHR j SWAP REPL END
  NEXT
≫ ≫ '→UPPER' STO

≪ 1 OVER SIZE FOR j 
     DUP j DUP SUB
     IF DUP "A" < OVER "Z" > OR THEN DROP
     ELSE NUM 32 + CHR j SWAP REPL END
  NEXT
≫ ≫ '→LOWER' STO
"alphaBETA" →UPPER
"alphaBETA" →LOWER
Output:
2: "ALPHABETA"
1: "alphabeta"

Ruby

"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"

"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".capitalize # => "Alphabeta"

These methods used to affect ASCII letters A-Z and a-z only. From Ruby 2.4 onward however, these methods support Full Unicode case mapping, suitable for most languages, by default. (Options can be specified for Turkic, Lithuanian and ascii)

Works with: Ruby version 2.4
'ĥåçýджк'.upcase  # => "ĤÅÇÝДЖК"

Rust

Works with: Rust version 1.3
fn main() {
    println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
    println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño
}

Scala

val s="alphaBETA"
println(s.toUpperCase)   //-> ALPHABETA
println(s.toLowerCase)   //-> alphabeta
println(s.capitalize)    //-> AlphaBETA
println(s.reverse)       //-> ATEBahpla

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"

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

Seed7

writeln(upper("alphaBETA"));
writeln(lower("alphaBETA"));

SenseTalk

set letters to "alphaBETA"
put lowercase of letters // alphabeta
put uppercase of letters // ALPHABETA
put capitalized of letters // Alphabeta

repeat with each character of letters by reference
	if it is an uppercase
		set it to lowercase of it
	else
		set it to uppercase of it
	end if
end repeat

put letters //ALPHAbeta

Sidef

say "alphaBETA".lc;             #=> alphabeta
say "alphaBETA".uc;             #=> ALPHABETA
say "alphaBETA".tc;             #=> AlphaBETA
say "alpha BETA".wc;            #=> Alpha Beta
say "alpha BETA".tc;            #=> Alpha BETA
say "alpha BETA".tclc;          #=> Alpha beta

Simula

TEXT soup, lower;
soup :- "alphaBETA";
lower :- LOWCASE(COPY(soup)); ! COPY, else soup is changed;
OutText("upper: "); OutText(UPCASE("alphaBETA"));
OutText(", lower: "); OutText(lower);
OutText(", soup: "); OutText(soup); Outimage;

Slate

'alphaBETA' toLowercase.
'alphaBETA' toUppercase.

Smalltalk

'ALPHAbeta' asUppercase  "->'ALPHABETA' "
'ALPHAbeta' asLowercase "-> 'alphabeta' "
Works with: Smalltalk/X
'alphabeta' asUppercaseFirst "-> 'Alphabeta' "

Unicode (notice, that this cannot be done simply with a straight forward "ch := ch -$a + $A" loop):

Works with: Smalltalk/X

(may work with other dialects too, but I have not verified)

'αβγω'  asUppercase -> 'ΑΒΓΩ'
'ĥåçýджк' asUppercase "->  'ĤÅÇÝДЖК'
'abcäöüáéíýıijńǵȅȇȉ' asUppercase -> 'ABCÄÖÜÁÉÍÝIIJŃǴȄȆȈ'

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

An alternative way of constructing the above that groups related functions together in a denser display:

        define('UC(STR)')
        define('LC(STR)')
        define('UCFIRST(STR)')
        define('SWAPC(STR)')                               :(CASES.END)
UC      uc = replace(str,&lcase,&ucase)                    :(RETURN)
LC      lc = replace(str,&ucase,&lcase)                    :(RETURN)
UCFIRST str len(1) . ch = uc(ch) ; ucfirst = str           :(RETURN)
SWAPC   swapc = replace(str, &ucase &lcase, &lcase &ucase) :(RETURN)
CASES.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

SparForte

As a structured script.

#!/usr/local/bin/spar
pragma annotate( summary, "stringcase" )
              @( description, "Take the string 'alphaBETA', and demonstrate how to" )
              @( description, "convert it to UPPER-CASE and lower-case. Use the" )
              @( description, "default encoding of a string literal or plain ASCII if" )
              @( description, "there is no string literal in your language. Show any" )
              @( description, "additional case conversion functions (e.g. swapping" )
              @( description, "case, capitalizing the first letter, etc.) that may be" )
              @( description, "included in the library of your language. " )
              @( category, "tutorials" )
              @( author, "Ken O. Burtch" )
              @( see_also, "http://rosettacode.org/wiki/String_case" );
pragma license( unrestricted );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure stringcase is
  s : constant string := "alphaBETA";
begin
  ? strings.to_upper( s );
  ? strings.to_lower( s );
  ? strings.to_proper( s );
end stringcase;

SQL

Works with: MS SQL version 2005
declare @s varchar(10)
set @s = 'alphaBETA'
print upper(@s)
print lower(@s)

SQL PL

Works with: Db2 LUW

With SQL only:

values upper('alphaBETA');
values lower('alphaBETA');
values initcap('alphaBETA');
-- Within a SQL query.
select upper('alphaBETA') from sysibm.sysdummy1;

Output:

db2 -t
db2 => values upper('alphaBETA');

1        
---------
ALPHABETA

  1 record(s) selected.

db2 => values lower('alphaBETA');

1        
---------
alphabeta

  1 record(s) selected.

db2 => values initcap('alphaBETA');

1        
---------
Alphabeta

  1 record(s) selected.
db2 => select upper('alphaBETA') from sysibm.sysdummy1;

1        
---------
ALPHABETA

  1 record(s) selected.

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

Stata

Use strupper and strlower to change case of ASCII characters. Use ustrupper and ustrlower to change case of all Unicode letters.

. scalar s="alphaBETA"
. di strupper(s)
ALPHABETA
. di strlower(s)
alphabeta

Notice there may be some difficulties with Unicode characters. In the following, the uppercase sigma is correctly converted back to the lowercase variant, but the iota subscript is not.

. scalar a="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. scalar b=ustrupper(a)
. di b
ἘΝ ἈΡΧΗ͂Ι ἘΠΟΊΗΣΕΝ Ὁ ΘΕῸΣ ΤῸΝ ΟΥ̓ΡΑΝῸΝ ΚΑῚ ΤῊΝ ΓΗ͂Ν
. di ustrlower(b)
ἐν ἀρχῆι ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν

Swift

import Foundation

println("alphaBETA".uppercaseString)
println("alphaBETA".lowercaseString)
println("foO BAr".capitalizedString)
Output:
ALPHABETA
alphabeta
Foo Bar

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

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

TorqueScript

 $string = "alphaBETA";
 $upperCase = strUpr($string);
 $lowerCase = strLwr($string);

Transd

#lang transd

MainModule: {
    _start: (λ 
        (with s "alphaBETA"
            (lout (toupper s))
            (lout (tolower s)))
    )
}
Output:
ALPHABETA
alphabeta

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

UNIX Shell

Works with: Bourne 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.

Bash

Works with: bash
s="alphaBETA"
echo ${s^^}     # => ALPHABETA
echo ${s,,}     # => alphabeta
echo ${s^}      # => AlphaBETA

Z Shell

Works with: zsh
s="alphaBETA"
echo ${s:u}     # => ALPHABETA
echo ${s:l}     # => alphabeta

Ursa

out (lower "alphaBETA") endl console
out (upper "alphaBETA") endl console

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

Vala

string s = "alphaBeta";
// stores ALPHABETA to string
string s_upper = s.up();
// stores alphabeta to string
string s_lower = s.down();

VBA

Function StringCase()
Dim s As String
s = "alphaBETA"
Debug.Print UCase(s)
Debug.Print LCase(s)
Debug.Print WorksheetFunction.Proper(s)
End Function

Output:

ALPHABETA
alphabeta
Alphabeta

VBScript

Dim MyWord
MyWord = UCase("alphaBETA")   ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA")   ' Returns "alphabeta"

Vedit macro language

#1 = CP
IT("alphaBETA")
Case_Upper_Block(#1, CP)
Case_Lower_Block(#1, CP)

V (Vlang)

Translation of: go
fn show(s string) {
    println('string: $s len: $s.len')
    println('All upper case: ${s.to_upper()}')
    println('All lower case: ${s.to_lower()}')
    println('Title words:    ${s.title()}')
    println('')
}

fn main(){
    show('alphaBETA')
    show('alpha BETA')
    show('DŽLjnj')
    show("o'hare O'HARE o’hare don't")
}

Output:

string: alphaBETA len: 9
All upper case: ALPHABETA
All lower case: alphabeta
Title words:    AlphaBETA

string: alpha BETA len: 10
All upper case: ALPHA BETA
All lower case: alpha beta
Title words:    Alpha BETA

string: DŽLjnj len: 6
All upper case: DŽLjnj
All lower case: DŽLjnj
Title words:    DŽLjnj

string: o'hare O'HARE o’hare don't len: 28
All upper case: O'HARE O'HARE O’HARE DON'T
All lower case: o'hare o'hare o’hare don't
Title words:    O'hare O'HARE O’hare Don't

Wren

Library: Wren-str

The 'Str' class supports the following methods:

  1. lower - converts all letters to lower case
  2. upper - converts all letters to upper case
  3. capitalize - converts only the first letter to upper case
  4. title - converts the first letter of each word to upper case
  5. swapCase - swaps the case of each letter

However, support is limited to letters which have both lower and upper case variants with codepoints < 256. This means that the lower case letters 'ß' and 'ÿ' are never changed by these methods. Although it would be possible to regard 'SS' as the upper case equivalent of 'ß', unfortunately this might not 'round-trip' and would not be compatible with the Char.upper method in any case. It has not therefore been done.

The 'Utf8' class recently acquired the first four of the above methods though with considerably wider (albeit still incomplete) Unicode coverage. In particular the upper case variants 'ẞ' and 'Ÿ' are now supported - the former was introduced into official German orthography in 2017 (though is optional) and, of course, now round-trips. Title case for 4 supported digraphs is automatically applied by the capitalize or title methods when they are the first character of the string (or, word, in the case of the latter).

import "./str" for Str, Utf8

var strs = ["alphaBETA", "ação", "o'hare O'HARE o’hare don't"]
System.print("Using 'Str' class methods:")
for (s in strs) {
    System.print("  original   : %(s)")
    System.print("  lower      : %(Str.lower(s))")
    System.print("  upper      : %(Str.upper(s))")
    System.print("  capitalize : %(Str.capitalize(s))")
    System.print("  title      : %(Str.title(s))")
    System.print("  swapCase   : %(Str.swapCase(s))")
    System.print()
}
var strs2 = ["Stroßbùrri", "ĥåçýджк", "DŽLjnj"]
System.print("Using 'Utf8' class methods:")
for (s in strs2) {
    System.print("  original   : %(s)")
    System.print("  lower      : %(Utf8.lower(s))")
    System.print("  upper      : %(Utf8.upper(s))")
    System.print("  capitalize : %(Utf8.capitalize(s))")
    System.print("  title      : %(Utf8.title(s))")
    System.print()
}
Output:
Using 'Str' class methods:
  original   : alphaBETA
  lower      : alphabeta
  upper      : ALPHABETA
  capitalize : AlphaBETA
  title      : AlphaBETA
  swapCase   : ALPHAbeta

  original   : ação
  lower      : ação
  upper      : AÇÃO
  capitalize : Ação
  title      : Ação
  swapCase   : AÇÃO

  original   : o'hare O'HARE o’hare don't
  lower      : o'hare o'hare o’hare don't
  upper      : O'HARE O'HARE O’HARE DON'T
  capitalize : O'hare O'HARE o’hare don't
  title      : O'hare O'HARE O’hare Don't
  swapCase   : O'HARE o'hare O’HARE DON'T

Using 'Utf8' class methods:
  original   : Stroßbùrri
  lower      : stroßbùrri
  upper      : STROẞBÙRRI
  capitalize : Stroßbùrri
  title      : Stroßbùrri

  original   : ĥåçýджк
  lower      : ĥåçýджк
  upper      : ĤÅÇÝДЖК
  capitalize : Ĥåçýджк
  title      : Ĥåçýджк

  original   : DŽLjnj
  lower      : džljnj
  upper      : DŽLJNJ
  capitalize : DžLjnj
  title      : DžLjnj

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

Z80 Assembly

The English alphabet is a subset of the ASCII character set, and the upper and lower case letters are 32 bytes apart. Bit 5 "toggles" the case of any letter in this range. Assuming your string exists in RAM, these subroutines are all that is needed to switch the string from upper to lower case, and vice versa. The first two functions are destructive, meaning that you cannot recover the original string after using them. The ToggleCase function can be performed twice on the same string to get the original string back.

ToUpperCase:
	;INPUT:
	;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
	;OVERWRITES THE STRING YOU INPUT WITH THE UPPERCASE VERSION
	ld bc,&617A		;lower case ascii range
loop_toUpperCase:
	ld a,(hl)
	or a
	ret z
	call CompareRange_Inclusive	;is this a lower case letter?
	jr c,skipUpperCase		;if not, don't change it!
		and %11011111		;change to upper case	
		ld (hl),a		;store back in string
skipUpperCase:
	inc hl
	jr loop_toUpperCase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToLowerCase:
	;INPUT:
	;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
	;OVERWRITES THE STRING YOU INPUT WITH THE LOWERCASE VERSION
	ld bc,&415A		;upper case ascii range
loop_toLowerCase:
	ld a,(hl)
	or a
	ret z
	call CompareRange_Inclusive
	jr c,skipLowerCase
		or %00100000
		ld (hl),a
skipLowerCase:
	inc hl
	jr loop_toLowerCase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
	;INPUT:
	;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
	;INVERTS THE CASE OF ALL ALPHABET CHARACTERS IN THE STRING
	ld bc,&415A		
loop_toggleCase:
	ld a,(hl)
	or a
	ret z
	call CompareRange_Inclusive
	jr nc,toggle
        push bc
             ld bc,&617A
             call CompareRange_Inclusive
        pop bc
        jr c, skipToggleCase
toggle:
		xor %00100000
		ld (hl),a
skipToggleCase:
	inc hl
	jr loop_toggleCase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CompareRange_Inclusive:
	;returns CF CLEAR if B <= A <= C, and CF SET otherwise.
	cp b
	ret c	;if carry set, A < B thus out of range.
		push de
			ld e,a
			ld a,c
			ld c,e	;swap A with C
			
			cp c	;compare C to A. Signs are reversed.
			;if carry set, "A" < "C" which means original C < original A. Thus out of range.
			;if carry clear, we are in range.
			
			ld e,a	;now put A and C back where they belong.
			ld a,c
			ld c,e	;none of this affects the flags, so the compare is still valid.
		pop de
		ret			
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Output:
ALPHABETA
alphabeta
ALPHAbeta

zkl

s:="alphaBETA";
s.toLower(); //--> "alphabeta"
s.toUpper(); //--> "ALPHABETA"

Zig

const std = @import("std");

pub fn main() !void {
    const stdout_wr = std.io.getStdOut().writer();
    const string = "alphaBETA";
    var lower: [string.len]u8 = undefined;
    var upper: [string.len]u8 = undefined;
    for (string) |char, i| {
        lower[i] = std.ascii.toLower(char);
        upper[i] = std.ascii.toUpper(char);
    }
    try stdout_wr.print("lower: {s}\n", .{lower});
    try stdout_wr.print("upper: {s}\n", .{upper});

    // TODO use https://github.com/jecolon/zigstr
}

Zoea

program: uppercase
  input: 'FOObar'
  output: 'FOOBAR'

program: lowercase
  input: 'FOObar'
  output: 'foobar'
Output:
ALPHABETA
alphabeta

Zoea Visual

Lowercase and Uppercase