String case: Difference between revisions
Content deleted Content added
Added Ed |
|||
(395 intermediate revisions by more than 100 users not shown) | |||
Line 1:
{{task|
;Task:
Take the string '''alphaBETA''' and demonstrate how to convert it to:
:::* upper-case and
:::* lower-case
<br>
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.
{{Template:Strings}}
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V s = ‘alphaBETA’
print(s.uppercase())
print(s.lowercase())</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
</pre>
=={{header|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').
<syntaxhighlight lang="360asm">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</syntaxhighlight>
{{out}}
<pre>
alphaBETA
ALPHABETA
alphabeta
</pre>
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.
<syntaxhighlight lang="360asm">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</syntaxhighlight>
{{out}}
<pre>
alphaBETA
ALPHABETA
alphabeta
</pre>
=={{header|4D}}==
<syntaxhighlight lang="4d">$string:="alphaBETA"
$uppercase:=Uppercase($string)
$lowercase:=Lowercase($string)</syntaxhighlight>
=={{header|6502 Assembly}}==
<syntaxhighlight lang="text"> .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 </syntaxhighlight>
Output:
<pre>
Alpha, BETA, gamma, {[(<123@_>)]}.
ALPHA, BETA, GAMMA, {[(<123@_>)]}.
alpha, beta, gamma, {[(<123@_>)]}.</pre>
=={{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.
<syntaxhighlight lang="68000devpac">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</syntaxhighlight>
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm"> 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,'$'</syntaxhighlight>
{{out}}
<pre>alphaBETA
ALPHABETA
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!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_case.png Screenshot from Atari 8-bit computer]
<pre>
Original string: "alphaBETA"
Upper-case string: "ALPHABETA"
Lower-case string: "alphabeta"
</pre>
=={{header|ActionScript}}==
=={{header|Ada}}==
<syntaxhighlight lang="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;</syntaxhighlight>
=={{header|ALGOL 68}}==
{{trans|C|Note: This specimen retains the original [[#C|C]] coding style.}}
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}}
{{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''.}}
<syntaxhighlight lang="algol68">#!/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
# Operators can be defined in ALGOL 68 #
OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper;
# upper-cases s in place #
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))
)</syntaxhighlight>
Output:
<pre>
uppercase: ALPHABETA
lowercase: alphabeta
</pre>
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">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.</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="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
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|APL}}==
Line 86 ⟶ 639:
(A,⎕AV)[(a,⎕AV)⍳'alphaBETA']
ALPHABETA
{{works with|APL}}
In the following example, puntuation is not covered. It is substituted by '*'.
<syntaxhighlight lang="apl">
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*
</syntaxhighlight>
==={{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.
<syntaxhighlight lang="apl">
⎕C 'Πέτρος is using APL!'
πέτροσ is using apl!
1 ⎕C 'Πέτρος is using APL!'
ΠΈΤΡΟΣ IS USING APL!
</syntaxhighlight>
Note: The I-Beam operator with code 819 is now deprecated in favor of the system function <code>⎕C</code>.
=={{header|AppleScript}}==
{{Trans|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.
<syntaxhighlight lang="applescript">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</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}</syntaxhighlight>
=={{header|Arbre}}==
<syntaxhighlight lang="arbre">main():
uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io</syntaxhighlight>
Output:
<pre>
ALPHABETA
alphabeta
</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}}==
<syntaxhighlight lang="rebol">str: "alphaBETA"
print ["uppercase :" upper str]
print ["lowercase :" lower str]
print ["capitalize :" capitalize str]</syntaxhighlight>
{{out}}
<pre>uppercase : ALPHABETA
lowercase : alphabeta
capitalize : AlphaBETA</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">a := "alphaBETA"
StringLower, b, a ; alphabeta
StringUpper, c, a ; ALPHABETA
StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"</syntaxhighlight>
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">$sString = "alphaBETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sLowercase = StringLower($sString) ;"alphabeta"</syntaxhighlight>
=={{header|Avail}}==
<syntaxhighlight lang="avail">Print: uppercase "alphaBETA";
Print: lowercase "alphaBETA";</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">BEGIN {
a = "alphaBETA";
print toupper(a), tolower(a)
}</syntaxhighlight>
Capitalize:
<syntaxhighlight lang="awk">BEGIN {
a = "alphaBETA";
print toupper(substr(a, 1, 1)) tolower(substr(a, 2))
}</syntaxhighlight>
=={{header|BASIC}}==
{{works with|
==={{header|
<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$
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}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"STRINGLIB"
original$ = "alphaBETA"
PRINT "Original: " original$
PRINT "Lower case: " FN_lower(original$)
PRINT "Upper case: " FN_upper(original$)
PRINT "Title case: " FN_title(original$)</syntaxhighlight>
Output:
<pre>Original: alphaBETA
Lower case: alphabeta
Upper case: ALPHABETA
Title case: AlphaBETA</pre>
==={{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:
* 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 <code>ASC("A")</code> returns <code>65</code>, and printing the result of <code>ASC("♠")</code> (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 <code>ASC</code> 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'''
<syntaxhighlight lang="commodorebasic">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$</syntaxhighlight>
{{output}}
<pre>
The original string is:
alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta
ready.
█</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}}===
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "String: ":TX$
110 PRINT "Lower case: ";LCASE$(TX$)
120 PRINT "Upper case: ";UCASE$(TX$)</syntaxhighlight>
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
{{works with|Run BASIC}}
<syntaxhighlight lang="lb">
input$ ="alphaBETA"
print input$
print upper$( input$)
print lower$( input$)
end
</syntaxhighlight>
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">s$ = "alphaBETA"
upper$ = UCase(s$) ;uppercase
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}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="runbasic">a$ ="alphaBETA"
print a$ '=> alphaBETA
print upper$(a$) '=> ALPHABETA
print lower$(a$) '=> alphabeta</syntaxhighlight>
==={{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.
==={{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}}===
{{works with|Visual Basic|2008}}
<syntaxhighlight lang="vbnet">' Define 's'
Dim s AS String = "alphaBETA"
' Change 's' to Upper Case.
s = s.ToUpper()
' Change 's' to Lower Case.
s = s.ToLower()</syntaxhighlight>
<syntaxhighlight lang="ti83b">:"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</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}}==
<syntaxhighlight lang="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))
$)</syntaxhighlight>
{{out}}
<pre> String: alphaBETA
Uppercase: ALPHABETA
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}}==
{{works with|befungee}}
Converts to uppercase only; lowercase is done in a similar way so I chose not to add it.
<syntaxhighlight lang="befunge">"ATEBahpla" > : #v_ 25* , @ >48*-v
> :: "`"` \"{"\` * | > , v
> ^
^ <</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}}==
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.
<syntaxhighlight lang="bracmat"> "alphaBETA":?s
& out$str$(upp$!s \n low$!s)</syntaxhighlight>
Output:
<pre>ALPHABETA
alphabeta</pre>
=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">
blsq ) "alphaBETA"^^zz\/ZZ
"ALPHABETA"
"alphabeta"
</syntaxhighlight>
=={{header|C}}==
The <tt>tolower</tt> and <tt>toupper</tt> functions are locale-aware.
<syntaxhighlight lang="c">/* Demonstrate toupper and tolower for
standard C strings.
This does not work for multibyte character sets. */
#include <ctype.h>
#include <stdio.h>
/
void str_toupper(char *s)
{
Line 116 ⟶ 1,259:
/
void str_tolower(char *s)
{
Line 134 ⟶ 1,277:
printf("lowercase: %s\n", t);
return 0;
}</syntaxhighlight>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
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);
}
}</syntaxhighlight>
Title case is a little different:
<syntaxhighlight lang="csharp">System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));</syntaxhighlight>
=={{header|C++}}==
Line 144 ⟶ 1,316:
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.
<syntaxhighlight lang="cpp">#include <algorithm>
#include <
#include <cctype>
/// \brief in-place convert string to upper case
Line 163 ⟶ 1,336:
str.begin(),
(int(*)(int)) std::tolower);
}</syntaxhighlight>
Here is sample usage code:
<syntaxhighlight lang="cpp">#include <iostream>
#include <
using namespace std;
Line 179 ⟶ 1,351:
cout << foo << endl;
return 0;
}</syntaxhighlight>
=={{header|
<syntaxhighlight lang="lisp">(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string))</syntaxhighlight>
=={{header|CMake}}==
<syntaxhighlight lang="cmake">string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}")</syntaxhighlight>
<pre>-- Uppercase: ALPHABETA
-- Lowercase: alphabeta</pre>
=={{header|COBOL}}==
===Standard-compliant Methods===
<syntaxhighlight lang="cobol"> 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
.</syntaxhighlight>
===Compiler Extensions===
<syntaxhighlight lang="cobol"> 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
.</syntaxhighlight>
=={{header|ColdFusion}}==
converting a string literal
converting the value of a variable
=={{header|Common Lisp}}==
You can use the ''string-upcase'' function to perform upper casing:
and you can do lower casing by using ''string-downcase'':
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
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.
</syntaxhighlight>
Execute: ^Q AlphaBeta.Do<br/>
Output:
<pre>
Uppercase:> ALPHABETA
Lowercase:> alphabeta
</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}}==
<syntaxhighlight lang="d">void main() {
import std.stdio, std.string;
immutable s = "alphaBETA";
s.toUpper.writeln;
}</syntaxhighlight>
{{out}}
<pre>ALPHABETA
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}}==
<syntaxhighlight lang="dbl">
OPEN (1,O,'TT:') ;open video
STR="alphaBETA"
LOCASE STR
DISPLAY (1,STR,10) ;alphabeta
UPCASE STR
DISPLAY (1,STR,10) ;ALPHABETA</syntaxhighlight>
=={{header|Delphi}}[[Category:Object Pascal]]==
<syntaxhighlight lang="pascal">writeln(uppercase('alphaBETA'));
writeln(lowercase('alphaBETA'));</syntaxhighlight>
=={{header|DWScript}}==
<syntaxhighlight lang="delphi">PrintLn(UpperCase('alphaBETA'));
PrintLn(LowerCase('alphaBETA'));</syntaxhighlight>
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">let str = "alphaBETA"
print("Lower case: ", str.Lower(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Capitalize: ", str.Capitalize(), separator: "")</syntaxhighlight>
=={{header|E}}==
<syntaxhighlight lang="e">["alphaBETA".toUpperCase(),
"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}}==
EchoLisp includes the usual case conversion functions and the '''randcase''' function : random case
<syntaxhighlight lang="scheme">
(string-downcase "alphaBETA")
→ "alphabeta"
(string-upcase "alphaBETA")
→ "ALPHABETA"
(string-titlecase "alphaBETA")
→ "Alphabeta"
(string-randcase "alphaBETA")
→ "alphaBEtA"
(string-randcase "alphaBETA")
→ "AlPHaBeTA"
</syntaxhighlight>
=={{header|ECL}}==
<syntaxhighlight lang="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);</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|Ed}}==
Searching for any lowercase or uppercase character is possible with either [a-z] or [A-Z] (or [:lower:] or [:upper:]) but substitution is not possible on character classes, in this instance, because there is no "to lower" or "to upper" function[ality]. The literal problem may be solved, however. Take the input file '''in''':
<pre>
alphaBETA
alphaBETA
alphaBETA
</pre>
With the following script, saved as '''String_case.ed''':
<syntaxhighlight lang="ed">
1s/a/A/g
1s/l/L/
1s/p/P/
1s/h/H/
2s/B/b/
2s/E/e/
2s/T/t/
2s/A/a/
3s/a/A/
%p
Q
</syntaxhighlight>
... and the command line:
<pre>
ed -s in < String_case.ed
</pre>
{{out}}
<pre>
ALPHABETA
alphabeta
AlphaBETA
</pre>
... which illustrates changing line 1's alphaBETA to all uppercase, line 2's alphaBETA to all lower case, and line 3's alphaBETA to have only the initial letter uppercase.
=={{header|Elena}}==
ELENA 6.x:
<syntaxhighlight lang="elena">import system'culture;
public program()
{
string s1 := "alphaBETA";
console.writeLine(s1.toLower(currentLocale));
console.writeLine(s1.toUpper(currentLocale));
console.readChar()
}</syntaxhighlight>
=={{header|Elixir}}==
The String module provides the following functions:
<syntaxhighlight lang="elixir">
String.downcase("alphaBETA")
# => alphabeta
String.upcase("alphaBETA")
# => ALPHABETA
String.capitalize("alphaBETA")
# => Alphabeta
</syntaxhighlight>
As with most String functions in Elixir, these are fully compatible with Unicode.
<syntaxhighlight lang="elixir">
String.downcase("αΒ")
# => αβ
String.upcase("αΒ")
# => ΑΒ
String.capitalize("αΒ")
# => Αβ
String.upcase("ß")
# => SS
</syntaxhighlight>
=={{header|Elm}}==
<syntaxhighlight lang="elm">import String exposing (toLower, toUpper)
s = "alphaBETA"
lower = toLower s
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}}==
<syntaxhighlight lang="erlang">string:to_upper("alphaBETA").
string:to_lower("alphaBETA").</syntaxhighlight>
=={{header|Excel}}==
Take 3 cells, say A1,B1 and C1. In B1 type :
<syntaxhighlight lang="excel">
=LOWER(A1)
</syntaxhighlight>
and in C1 :
<syntaxhighlight lang="excel">
=UPPER(A1)
</syntaxhighlight>
For the stated input in A1, the result will be :
<syntaxhighlight lang="text">
alphaBETA alphabeta ALPHABETA
</syntaxhighlight>
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">
let s = "alphaBETA"
let upper = s.ToUpper()
let lower = s.ToLower()
</syntaxhighlight>
=={{header|Factor}}==
"alphaBETA" >title ! "Alphabeta"
"ß" >case-fold ! "ss"</syntaxhighlight>
=={{header|Falcon}}==
<syntaxhighlight lang="falcon">printl("alphaBETA".lower())
printl("alphaBETA".upper())</syntaxhighlight>
=={{header|Fantom}}==
<syntaxhighlight lang="fantom">
fansh> a := "alphaBETA"
alphaBETA
fansh> a.upper // convert whole string to upper case
ALPHABETA
fansh> a.lower // convert whole string to lower case
alphabeta
fansh> a.capitalize // make sure first letter is capital
AlphaBETA
fansh> "BETAalpha".decapitalize // make sure first letter is not capital
bETAalpha
</syntaxhighlight>
=={{header|Forth}}==
Line 269 ⟶ 1,844:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 307 ⟶ 1,881:
end subroutine To_Lower
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.
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: <syntaxhighlight lang="fortran"> 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</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 <syntaxhighlight lang="fortran"> DO I = 1,LEN(TEXT)
TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))
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.
Here a complete example, using functions, and as far as I can tell, will work also with EBCDIC:
<syntaxhighlight lang="fortran">
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
</syntaxhighlight>
=={{header|Frink}}==
<syntaxhighlight lang="frink">
a = "alphaBETA"
println[lc[a]]
println[uc[a]]
</syntaxhighlight>
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:
<syntaxhighlight lang="frink">uc["Imbiß"] // Last char is \u00df</syntaxhighlight>
Produces:
<pre>IMBISS</pre>
As the Unicode standard for casing states, "it is important to note that no casing operations on strings are reversible:"
<syntaxhighlight lang="frink">lc[ uc["Imbiß"] ]</syntaxhighlight>
<pre>imbiss</pre>
=={{header|GAP}}==
<syntaxhighlight lang="gap">LowercaseString("alphaBETA");
UppercaseString("alphaBETA");</syntaxhighlight>
=={{header|GDScript}}==
{{works with|Godot|4.0.2}}
<syntaxhighlight lang="gdscript">
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
</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
to_camel_case: alphaBeta
to_pascal_case: AlphaBeta
to_snake_case: alpha_beta
</pre>
=={{header|GML}}==
<syntaxhighlight lang="gml">#define cases
{
x = 'alphaBETA';
y = string_upper(x); // returns ALPHABETA
z = string_lower(x); // returns alphabeta
show_message(y);
show_message(z);
}</syntaxhighlight>
=={{header|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.
<syntaxhighlight lang="go">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))
}</syntaxhighlight>
{{out}}
<pre>
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
</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>
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">def str = 'alphaBETA'
println str.toUpperCase()
println str.toLowerCase()</syntaxhighlight>
Output:
<pre>ALPHABETA
alphabeta</pre>
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.Char
s = "alphaBETA"
lower = map toLower s
upper = map toUpper s</syntaxhighlight>
=={{header|HicEst}}==
<syntaxhighlight lang="hicest">CHARACTER str = "alphaBETA"
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, UpperCase=1) </syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">procedure main()
write(map("alphaBETA"))
write(map("alphaBETA",&lcase,&ucase))
end</syntaxhighlight>
=={{header|IDL}}==
str = "alphaBETA"
print, str
Line 327 ⟶ 2,170:
=={{header|J}}==
Use standard utilities:
<syntaxhighlight lang="j"> toupper 'alphaBETA'
ALPHABETA
tolower 'alphaBETA'
alphabeta</syntaxhighlight>
or alternative definitions:
<syntaxhighlight lang="j">upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.)
lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)</syntaxhighlight>
For example:
<syntaxhighlight lang="j"> upper 'alphaBETA'
ALPHABETA
lower 'alphaBETA'
alphabeta</syntaxhighlight>
=={{header|Java}}==
The ''String'' class offers the ''toUpperCase'' and ''toLowerCase'' methods.
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>
<
Alternately
<syntaxhighlight lang="java">String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
//Also works with non-English characters with no modification
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß"</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>.
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">alert( "alphaBETA".toUpperCase() );
alert( "alphaBETA".
Output:
Line 358 ⟶ 2,216:
{{works with|NJS| 0.2.5}}
<
var uppercase = string.toUpperCase();
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}}==
'''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:
<syntaxhighlight lang="jq"># 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;
</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''':
<syntaxhighlight lang="jq">
"alphaBETA" | ascii_upcase
#=> "ALPHABETA"
"alphaBETA" | ascii_downcase
#=> "alphabeta"
jq -n '"á" | test("Á";"i")' # case-insensitive search
#=> true
</syntaxhighlight>
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">var msg = "alphaBETA";
;msg;
;msg.toUpperCase();
;msg.toLowerCase();
;msg.toTitle();
;msg.toLocaleUpperCase();
;msg.toLocaleLowerCase();</syntaxhighlight>
{{out}}
<pre>prompt$ jsish --U string-case.jsi
msg ==> alphaBETA
msg.toUpperCase() ==> ALPHABETA
msg.toLowerCase() ==> alphabeta
msg.toTitle() ==> Alphabeta
msg.toLocaleUpperCase() ==> ALPHABETA
msg.toLocaleLowerCase() ==> alphabeta</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">julia> uppercase("alphaBETA")
"ALPHABETA"
julia> lowercase("alphaBETA")
"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}}==
{{works with|Kona}}
<syntaxhighlight lang="k"> 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"
</syntaxhighlight>
{{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}}==
<syntaxhighlight lang="scala">// version 1.0.6
fun main(args: Array<String>) {
val s = "alphaBETA"
println(s.toUpperCase())
println(s.toLowerCase())
println(s.capitalize())
println(s.decapitalize())
}</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
AlphaBETA
alphaBETA
</pre>
=={{header|Lambdatalk}}==
Lambdatalk can take benefit from CSS rules.
<syntaxhighlight lang="scheme">
{span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta
{span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA
</syntaxhighlight>
=={{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}}==
<syntaxhighlight lang="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</syntaxhighlight>
=={{header|Lingo}}==
Lingo has no case conversion functions, but for ASCII strings they can e.g. be implemented like this:
<syntaxhighlight lang="lingo">----------------------------------------
-- 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</syntaxhighlight>
<syntaxhighlight lang="lingo">put toUpper("alphaBETA")
-- "ALPHABETA"
put toLower("alphaBETA")
-- "alphabeta"</syntaxhighlight>
=={{header|LiveCode}}==
<syntaxhighlight lang="livecode">put upper("alphaBETA") && lower("alphaBETA")
ALPHABETA alphabeta</syntaxhighlight>
=={{header|Logo}}==
print uppercase "alphaBETA ; ALPHABETA
print lowercase "alphaBETA ; alphabeta
=={{header|Lua}}==
<syntaxhighlight lang="lua">str = "alphaBETA"
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}}==
<syntaxhighlight lang="m4">define(`upcase', `translit(`$*', `a-z', `A-Z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')
define(`x',`alphaBETA')
upcase(x)
downcase(x)</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang="maple">str := "alphaBETA";
StringTools:-UpperCase(str);
StringTools:-LowerCase(str);</syntaxhighlight>
produces
<pre> alphabeta</pre>
<pre> ALPHABETA</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">str="alphaBETA";
ToUpperCase[str]
ToLowerCase[str]</syntaxhighlight>
{{out}}
<pre>ALPHABETA
alphabeta</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">>> upper('alphaBETA')
ans =
ALPHABETA
>> lower('alphaBETA')
ans =
alphabeta</syntaxhighlight>
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">supcase('alphaBETA');
sdowncase('alphaBETA');</syntaxhighlight>
=={{header|MAXScript}}==
Requires MAX 2008
<
print (toUpper str)
print (toLower str)</syntaxhighlight>
=={{header|Mercury}}==
The functions to_upper/1, to_lower/1, capitalize_first/1 and uncapitalize_first/1
only affect unaccented Latin characters.
<syntaxhighlight lang="text">:- 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.</syntaxhighlight>
=={{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).
<syntaxhighlight lang="metafont">vardef isbetween(expr a, i, f) =
if string a:
if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)):
true
else:
false
fi
else:
false
fi enddef;
vardef toupper(expr s) =
save ?; string ?; ? := ""; d := ASCII"A" - ASCII"a";
for i = 0 upto length(s)-1:
if isbetween(substring(i, i+1) of s, "a", "z"):
? := ? & char(ASCII(substring(i,i+1) of s) + d)
else:
? := ? & substring(i, i+1) of s
fi;
endfor
?
enddef;
vardef tolower(expr s) =
save ?; string ?; ? := ""; d := ASCII"a" - ASCII"A";
for i = 0 upto length(s)-1:
if isbetween(substring(i, i+1) of s, "A", "Z"):
? := ? & char(ASCII(substring(i,i+1) of s) + d)
else:
? := ? & substring(i, i+1) of s
fi;
endfor
?
enddef;</syntaxhighlight>
<syntaxhighlight lang="metafont">message toupper("alphaBETA");
message tolower("alphaBETA");
end</syntaxhighlight>
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">"alphaBETA" uppercase
"alphaBETA" lowercase
"alphaBETA" capitalize</syntaxhighlight>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower</syntaxhighlight>
{{out}}
<pre>
Upper Case of alphaBETA is ALPHABETA
Lower Case of alphaBETA is alphabeta
</pre>
=={{header|MIPS Assembly}}==
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:
;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</syntaxhighlight>
{{out}}
<pre>
alphaBETA ;original
ALPHABETA ;uppercase
alphabeta ;lowercase
ALPHAbeta ;toggled</pre>
=={{header|mIRC Scripting Language}}==
<syntaxhighlight lang="mirc">echo -ag $upper(alphaBETA)
echo -ag $lower(alphaBETA)</syntaxhighlight>
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE TextCase EXPORTS Main;
IMPORT IO, Text, ASCII;
PROCEDURE Upper(txt: TEXT): TEXT =
VAR
len := Text.Length(txt);
res := "";
BEGIN
FOR i := 0 TO len - 1 DO
res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)]));
END;
RETURN res;
END Upper;
PROCEDURE Lower(txt: TEXT): TEXT =
VAR
len := Text.Length(txt);
res := "";
BEGIN
FOR i := 0 TO len - 1 DO
res := Text.Cat(res, Text.FromChar(ASCII.Lower[Text.GetChar(txt, i)]));
END;
RETURN res;
END Lower;
BEGIN
IO.Put(Upper("alphaBETA\n"));
IO.Put(Lower("alphaBETA\n"));
END TextCase.</syntaxhighlight>
Output:
<pre>
ALPHABETA
alphabeta
</pre>
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
STRCASE(S)
SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SET LO="abcdefghijklmnopqrstuvwxyz"
WRITE !,"Given: "_S
WRITE !,"Upper: "_$TRANSLATE(S,LO,UP)
WRITE !,"Lower: "_$TRANSLATE(S,UP,LO)
QUIT
</syntaxhighlight>
Output:<pre>
USER>DO STRCASE^ROSETTA("alphaBETA")
Given: alphaBETA
Upper: ALPHABETA
Lower: alphabeta
</pre>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">string = "alphaBETA"
println upper(string)
println lower(string)</syntaxhighlight>
=={{header|Nemerle}}==
<syntaxhighlight lang="nemerle">using System.Console;
using System.Globalization;
module StringCase
{
Main() : void
{
def alpha = "alphaBETA";
WriteLine(alpha.ToUpper());
WriteLine(alpha.ToLower());
WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
}
}</syntaxhighlight>
=={{header|NetRexx}}==
<syntaxhighlight lang="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
</syntaxhighlight>
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
(upper-case "alphaBETA")
(lower-case "alphaBETA")
</syntaxhighlight>
=={{header|Nial}}==
=={{header|
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.
<syntaxhighlight lang="nim">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.</syntaxhighlight>
{{out}}
<pre>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</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}}==
<syntaxhighlight lang="objeck">
string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();
</syntaxhighlight>
=={{header|Objective-C}}==
{{works with|GNUstep}}
{{works with|Cocoa}}
<syntaxhighlight lang="objc">NSLog(@"%@", @"alphaBETA".uppercaseString);
NSLog(@"%@", @"alphaBETA".lowercaseString);
NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"</syntaxhighlight>
=={{header|OCaml}}==
<
let str = "alphaBETA" in
print_endline (String.capitalize_ascii str); (* AlphaBETA *)
;;</syntaxhighlight>
=={{header|Octave}}==
<syntaxhighlight lang="octave">s = "alphaBETA";
slc = tolower(s);
suc = toupper(s);
disp(slc);
disp(suc);</syntaxhighlight>
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">"alphaBETA" toUpper
"alphaBETA" toLower</syntaxhighlight>
=={{header|OpenEdge/Progress}}==
<syntaxhighlight lang="progress (openedge abl)">caps("alphaBETA")
lc("alphaBETA")
</syntaxhighlight>
=={{header|Oz}}==
Convert to upper/lower-case:
<syntaxhighlight lang="oz">declare
Str = "alphaBETA"
in
{System.showInfo {Map Str Char.toUpper}}
{System.showInfo {Map Str Char.toLower}}</syntaxhighlight>
Capitalize:
<syntaxhighlight lang="oz">declare
[StringX] = {Link ['x-oz://system/String.ozf']}
in
{System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"</syntaxhighlight>
=={{header|Pascal}}==
<syntaxhighlight lang="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.
</syntaxhighlight>
Demonstration:
<pre>
Original string : alphaBETA
Reversed case : ALPHAbeta
Upper case : ALPHABETA
Lower case : alphabeta
</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
var s := 'exAmpLe sTrinG';
s.ToLower.Println;
s.ToUpper.Println;
</syntaxhighlight>
{{out}}
<pre>
example string
EXAMPLE STRING
</pre>
=={{header|Peloton}}==
Iterating through the peerset
<syntaxhighlight lang="sgml"><@ ENU$$$LSTPSTLITLIT>UPP|
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@>
<@ SAY&&&LIT>alphaBETA</@>
</@></syntaxhighlight>
Same code in padded-out, variable-length English dialect
<syntaxhighlight lang="sgml"><# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP|
[<# SAY ELEMENT LIST>...</#>] <# SAY HELP ELEMENT LIST>...</#><# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|...</#>
<# SAY SUPERMACRO LITERAL>alphaBETA</#>
</#></syntaxhighlight>
Output.
<pre>[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
</pre>
=={{header|Perl}}==
{{works with|Perl|5.x}}
<syntaxhighlight lang="perl">my $string = "alphaBETA";
print
$string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta
print ucfirst($string), "\n"; # => "AlphaBETA"
print lcfirst("FOObar"), "\n"; # => "fOObar"</syntaxhighlight>
Also works in Perl 4 if the '''my''' is removed.
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<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: #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>
<!--</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.
=={{header|PHP}}==
<syntaxhighlight lang="php">$str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo
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</syntaxhighlight>
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
S = "alphaBETA",
println(to_uppercase(S)),
println(to_lowercase(S)).</syntaxhighlight>
{{out}}
<pre>ALPHABETA
alphabeta</pre>
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(let Str "alphaBETA"
(prinl (uppc Str))
(prinl (lowc Str)) )</syntaxhighlight>
=={{header|Pike}}==
Note: String.Elite.elite_string has an element of randomness, so the
output will differ from run to run.
<syntaxhighlight lang="pike">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));
</syntaxhighlight>
{{Out}}
<pre>
Upper: "ALPHABETA"
Lower: "alphabeta"
Capitalize: "AlphaBETA"
Silly: "Foo Bar Gazonk"
Elite: "fo() 8ar 6azo|\\||<"
</pre>
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.
<syntaxhighlight lang="pike">#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) );
}</syntaxhighlight>
{{Out}}
<pre>
Upper: ἈΡΧῇ ß
Lower: ἀρχῇ ß
</pre>
=={{header|PL/I}}==
<syntaxhighlight lang="pli">
declare s character (20) varying initial ('alphaBETA');
put skip list (uppercase(s));
put skip list (lowercase(s));
</syntaxhighlight>
<syntaxhighlight lang="pli">
/* 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') );
</syntaxhighlight>
=={{header|PL/SQL}}==
<syntaxhighlight lang="plsql">declare
vc VARCHAR2(40) := 'alphaBETA';
ivc VARCHAR2(40);
lvc VARCHAR2(40);
uvc VARCHAR2(40);
begin
ivc := INITCAP(vc); -- 'Alphabeta'
lvc := LOWER(vc); -- 'alphabeta'
uvc := UPPER(vc); -- 'ALPHABETA'
end; </syntaxhighlight>
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">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.</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
Alphabeta
</pre>
=={{header|Pop11}}==
<syntaxhighlight lang="pop11">lvars str = 'alphaBETA';
lowertoupper(str) =>
uppertolower(str) =></syntaxhighlight>
=={{header|Potion}}==
<syntaxhighlight lang="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</syntaxhighlight>
=={{header|Powerbuilder}}==
<syntaxhighlight lang="powerbuilder">string ls_string
ls_string = 'alphaBETA'
ls_string = Upper(ls_string)
ls_string = Lower(ls_string)</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$string = 'alphaBETA'
$lower = $string.ToLower()
$upper = $string.ToUpper()
$title = (Get-Culture).TextInfo.ToTitleCase($string)
$lower, $upper, $title
</syntaxhighlight>
{{Out}}
<pre>
alphabeta
ALPHABETA
Alphabeta
</pre>
=={{header|Python}}==
<syntaxhighlight lang="python">s = "alphaBETA"
print s.upper() # => "ALPHABETA"
print s.lower() # => "alphabeta"
print s.swapcase() # => "ALPHAbeta"
print "fOo bAR".capitalize() # => "Foo bar"
print "fOo bAR".title() # => "Foo Bar"
import string
print string.capwords("fOo bAR") # => "Foo Bar"</syntaxhighlight>
string.capwords() allows the user to define word separators, and by default behaves slightly differently than title().
<syntaxhighlight lang="python">print "foo's bar".title() # => "Foo'S Bar"
print string.capwords("foo's bar") # => "Foo's Bar"</syntaxhighlight>
=={{header|QB64}}==
<syntaxhighlight lang="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)</syntaxhighlight>
'''Optimized version:'''
<br>
''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.
<syntaxhighlight lang="vb">s$ = "alphaBETA"
PRINT "The original string: "; s$: PRINT
PRINT "Converted to lowercase: "; LCASE$(s$)
PRINT "Converted to uppercase: "; UCASE$(s$)</syntaxhighlight>
=={{header|Quackery}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{Out}}
<pre>patrick, i don't think wumbo is a real word.
PATRICK, I DON'T THINK WUMBO IS A REAL WORD.</pre>
=={{header|R}}==
<syntaxhighlight lang="r"> str <- "alphaBETA"
toupper(str)
tolower(str)</syntaxhighlight>
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(define example "alphaBETA")
(string-upcase example)
;"ALPHABETA"
(string-downcase example)
;"alphabeta"
(string-titlecase example)
;"Alphabeta"</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
In Raku, case modification is implemented as builtin subroutine or method:
<syntaxhighlight lang="raku" line>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
</syntaxhighlight>
Output:
<pre>ALPHA BETA
alpha beta
Alpha BETA
Alpha beta
Alpha Beta</pre>
=={{header|Raven}}==
<syntaxhighlight lang="raven">'alphaBETA' upper
'alhpaBETA' lower</syntaxhighlight>
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">print ["Original: " original: "alphaBETA"]
print ["Uppercase:" uppercase original]
print ["Lowercase:" lowercase original]</syntaxhighlight>
Output:
<pre>Original: alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta</pre>
=={{header|Red}}==
<syntaxhighlight lang="red">str: "alphaBETA"
>> uppercase str
== "ALPHABETA"
>> lowercase str
== "alphabeta"
>> uppercase/part str 5
== "ALPHAbeta"</syntaxhighlight>
=={{header|Retro}}==
<syntaxhighlight lang="retro">'alphaBETA s:to-upper s:put
'alphaBETA s:to-lower s:put</syntaxhighlight>
=={{header|REXX}}==
===with TRANSLATE BIF===
The following code will execute correctly in '''ASCII''' and '''EBCDIC.
<syntaxhighlight lang="rexx">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*/</syntaxhighlight>
===with PARSE UPPER & PARSE LOWER statements===
The following code will execute correctly in '''ASCII''' and '''EBCDIC.
<syntaxhighlight lang="rexx">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.*/</syntaxhighlight>
===with UPPER & LOWER BIFs===
The following code will execute correctly in '''ASCII''' and '''EBCDIC.
<syntaxhighlight lang="rexx">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).*/</syntaxhighlight>
===with UPPER statement===
The following code will execute correctly in '''ASCII''' and '''EBCDIC.
<syntaxhighlight lang="rexx">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.*/</syntaxhighlight>
===with capitalized words===
The following code will execute correctly in '''ASCII''' and '''EBCDIC.
<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",
"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. */</syntaxhighlight>
Some older REXXes don't have a '''changestr''' BIF, so one is included here ───► [[CHANGESTR.REX]]. <br>
{{out|output|:}}
<pre>
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.
</pre>
Note: there are many variant spellings of the Hebrew alphabet.
<br><br>
===with case swap===
The following code will execute correctly in '''ASCII''' and '''EBCDIC.
<syntaxhighlight lang="rexx">/*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. */</syntaxhighlight>
'''output'''
<pre>
alphaBETA
ALPHAbeta
</pre>
===version 2===
<syntaxhighlight lang="rexx">
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
</syntaxhighlight>
: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:
<syntaxhighlight lang="rexx">
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 */
</syntaxhighlight>
Translation to lowercase is not similarly possible because of 'SS'->'ß' or -> 'ss' ??
<br>
Note: Recently an uppercase ß was introduced in Austria. I haven't used it yet.
=={{header|Ring}}==
<syntaxhighlight lang="ring">
aString = "WELCOME TO THE ring programming language"
see lower(aString) + nl
see upper(aString) + nl
</syntaxhighlight>
=={{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}}==
<syntaxhighlight lang="ruby">"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".swapcase # => "ALPHAbeta"
"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)
{{works with|Ruby| 2.4}}
<syntaxhighlight lang="ruby">'ĥåçýджк'.upcase # => "ĤÅÇÝДЖК"</syntaxhighlight>
=={{header|Rust}}==
{{works with|Rust| 1.3}}
<syntaxhighlight lang="rust">fn main() {
println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño
}</syntaxhighlight>
=={{header|Scala}}==
<syntaxhighlight lang="scala">val s="alphaBETA"
println(s.toUpperCase) //-> ALPHABETA
println(s.toLowerCase) //-> alphabeta
println(s.capitalize) //-> AlphaBETA
println(s.reverse) //-> ATEBahpla</syntaxhighlight>
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">(define s "alphaBETA")
(list->string (map char-upcase (string->list s)))
(list->string (map char-downcase (string->list s)))</syntaxhighlight>
Using SRFI-13:
<syntaxhighlight lang="scheme">
> (define s "alphaBETA gammaDELTA")
> (string-upcase s) ;; turn all into upper case
"ALPHABETA GAMMADELTA"
> (string-downcase s) ;; turn all into lower case
"alphabeta gammadelta"
> (string-titlecase s) ;; capitalise start of each word
"Alphabeta Gammadelta"
</syntaxhighlight>
=={{header|Sed}}==
Piping through sed in bash:
<syntaxhighlight lang="bash">echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'</syntaxhighlight>
Other functions:
<syntaxhighlight lang="bash"># Invert case
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/'</syntaxhighlight>
GNU sed supports special sequences to change case:
<syntaxhighlight lang="bash">
# to uppercase
$ echo alphaBETA | sed 's/.*/\U&/'
ALPHABETA
# to lowercase
$ echo alphaBETA | sed 's/.*/\L&/'
alphabeta
</syntaxhighlight>
=={{header|Seed7}}==
writeln(upper("alphaBETA"));
writeln(lower("alphaBETA"));
=={{header|SenseTalk}}==
<syntaxhighlight lang="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
</syntaxhighlight>
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">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</syntaxhighlight>
=={{header|Simula}}==
<syntaxhighlight lang="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;</syntaxhighlight>
=={{header|Slate}}==
<syntaxhighlight lang="slate">'alphaBETA' toLowercase.
'alphaBETA' toUppercase.</syntaxhighlight>
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">'ALPHAbeta' asUppercase "->'ALPHABETA' "
'ALPHAbeta' asLowercase "-> 'alphabeta' "</syntaxhighlight>
{{works with|Smalltalk/X}}
{{works with|VisualWorks Smalltalk}}
<syntaxhighlight lang="smalltalk">'alphabeta' asUppercaseFirst "-> 'Alphabeta' "</syntaxhighlight>
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)
<syntaxhighlight lang="smalltalk">'αβγω' asUppercase -> 'ΑΒΓΩ'
'ĥåçýджк' asUppercase "-> 'ĤÅÇÝДЖК'
'abcäöüáéíýıijńǵȅȇȉ' asUppercase -> 'ABCÄÖÜÁÉÍÝIIJŃǴȄȆȈ'</syntaxhighlight>
=={{header|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.
<syntaxhighlight lang="snobol4"> define('uc(str)') :(uc_end)
uc uc = replace(str,&lcase,&ucase) :(return)
uc_end
define('lc(str)') :(lc_end)
lc lc = replace(str,&ucase,&lcase) :(return)
lc_end
define('ucfirst(str)ch') :(ucfirst_end)
ucfirst str len(1) . ch = uc(ch)
ucfirst = str :(return)
ucfirst_end
define('swapc(str)') :(swapc_end)
swapc str = replace(str,&ucase &lcase, &lcase &ucase)
swapc = str :(return)
swapc_end
* # Test and display
str = 'alphaBETA'
output = str
output = lc(str)
output = uc(str)
output = ucfirst(str)
output = swapc(str)
end</syntaxhighlight>
An alternative way of constructing the above that groups related functions together in a denser display:
<syntaxhighlight lang="snobol4"> 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</syntaxhighlight>
Output:
<pre>alphaBETA
alphabeta
ALPHABETA
AlphaBETA
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}}==
{{works with|MS SQL| 2005}}
<syntaxhighlight lang="sql">declare @s varchar(10)
set @s = 'alphaBETA'
print upper(@s)
print lower(@s)</syntaxhighlight>
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
With SQL only:
<syntaxhighlight lang="sql pl">
values upper('alphaBETA');
values lower('alphaBETA');
values initcap('alphaBETA');
-- Within a SQL query.
select upper('alphaBETA') from sysibm.sysdummy1;
</syntaxhighlight>
Output:
<pre>
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.
</pre>
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">val strupr = String.map Char.toUpper;
val strlwr = String.map Char.toLower;</syntaxhighlight>
Test
Line 512 ⟶ 3,742:
<i>val it = "alphabeta" : string</i>
=={{header|
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.
<syntaxhighlight lang="stata">. scalar s="alphaBETA"
. di strupper(s)
ALPHABETA
. di strlower(s)
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.
<syntaxhighlight lang="stata">. scalar a="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. scalar b=ustrupper(a)
. di b
ἘΝ ἈΡΧΗ͂Ι ἘΠΟΊΗΣΕΝ Ὁ ΘΕῸΣ ΤῸΝ ΟΥ̓ΡΑΝῸΝ ΚΑῚ ΤῊΝ ΓΗ͂Ν
. di ustrlower(b)
ἐν ἀρχῆι ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="swift">import Foundation
println("alphaBETA".uppercaseString)
println("alphaBETA".lowercaseString)
println("foO BAr".capitalizedString)</syntaxhighlight>
{{output}}
<pre>
ALPHABETA
alphabeta
Foo Bar
</pre>
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">set string alphaBETA
# three built-in case conversion commands
string tolower $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</syntaxhighlight>
=={{header|Toka}}==
needs ctype
Line 539 ⟶ 3,816:
" alphaBETA" string.toLower type cr
=={{header|
$string = "alphaBETA";
$upperCase = strUpr($string);
$lowerCase = strLwr($string);
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
MainModule: {
_start: (λ
(with s "alphaBETA"
(lout (toupper s))
(lout (tolower s)))
)
}</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
</pre>
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
string="alphaBETA"
lowercase =EXCHANGE(string," {&a} {-0-} ")
uppercase1=EXCHANGE(string," {&a} {-0+} ")
uppercase2=CAPS (string)
PRINT lowercase
PRINT uppercase1
PRINT uppercase2
</syntaxhighlight>
Output:
<pre>
alphabeta
ALPHABETA
ALPHABETA
</pre>
=={{header|Uiua}}==
{{works with|Uiua|0.11.1}}
<syntaxhighlight lang="uiua">
¯"alphaBETA" # swapcase
⌵"alphaBETA" # upper
¯⌵"alphaBETA" # lower
±"alphaBETA123" # case mask 1=upper, -1=lower, 0=neither
</syntaxhighlight>
{{out}}
<pre>
"ALPHAbeta"
"ALPHABETA"
"alphabeta"
[¯1 ¯1 ¯1 ¯1 ¯1 1 1 1 1 0 0 0]
</pre>
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
For System V tr:
<syntaxhighlight lang="bash">echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA
echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta</syntaxhighlight>
For [[BSD]] tr, [[GNU]] tr, or any [[POSIX]] system:
<syntaxhighlight lang="bash">echo alphaBETA | tr a-z A-Z # => ALPHABETA
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.
===Bash===
{{works with|bash}}
<syntaxhighlight lang="bash">s="alphaBETA"
echo ${s^^} # => ALPHABETA
echo ${s,,} # => alphabeta
echo ${s^} # => AlphaBETA</syntaxhighlight>
===Z Shell===
{{works with|zsh}}
<syntaxhighlight lang="bash">s="alphaBETA"
echo ${s:u} # => ALPHABETA
echo ${s:l} # => alphabeta</syntaxhighlight>
=={{header|Ursa}}==
<syntaxhighlight lang="ursa">out (lower "alphaBETA") endl console
out (upper "alphaBETA") endl console</syntaxhighlight>
=={{header|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.
<syntaxhighlight lang="ursala">#import std
to_upper = * -:~& ~=`A-~p letters
to_lower = * -:~& ~=`A-~rlp letters
#show+
examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'></syntaxhighlight>
output:
<pre>ALPHABETA
alphabeta</pre>
=={{header|Vala}}==
<syntaxhighlight lang="vala">
string s = "alphaBeta";
// stores ALPHABETA to string
string s_upper = s.up();
// stores alphabeta to string
string s_lower = s.down();
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">Function StringCase()
Dim s As String
s = "alphaBETA"
Debug.Print UCase(s)
Debug.Print LCase(s)
Debug.Print WorksheetFunction.Proper(s)
End Function</syntaxhighlight>
Output:
<pre>ALPHABETA
alphabeta
Alphabeta</pre>
=={{header|VBScript}}==
<syntaxhighlight lang="vbscript">Dim MyWord
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA") ' Returns "alphabeta"</syntaxhighlight>
=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">#1 = CP
IT("alphaBETA")
Case_Upper_Block(#1, CP)
Case_Lower_Block(#1, CP)</syntaxhighlight>
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">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")
}</syntaxhighlight>
Output:
<pre>
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
</pre>
=={{header|Wren}}==
{{libheader|Wren-str}}
The 'Str' class supports the following methods:
# ''lower'' - converts all letters to lower case
# ''upper'' - converts all letters to upper case
# ''capitalize'' - converts only the first letter to upper case
# ''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}}
<pre>
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
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="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);
]</syntaxhighlight>
Output:
<pre>
ALPHABETA
alphabeta
</pre>
=={{header|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 <code>ToggleCase</code> function can be performed twice on the same string to get the original string back.
<syntaxhighlight lang="z80">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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;</syntaxhighlight>
{{out}}
<pre>
ALPHABETA
alphabeta
ALPHAbeta
</pre>
=={{header|zkl}}==
<syntaxhighlight lang="zkl">s:="alphaBETA";
s.toLower(); //--> "alphabeta"
s.toUpper(); //--> "ALPHABETA"</syntaxhighlight>
{{omit from|Openscad}}
{{omit from|PARI/GP|No real capacity for string manipulation}}
=={{header|Zig}}==
<syntaxhighlight lang="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://codeberg.org/dude_the_builder/zigstr
}</syntaxhighlight>
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: uppercase
input: 'FOObar'
output: 'FOOBAR'
program: lowercase
input: 'FOObar'
output: 'foobar'
</syntaxhighlight>
{{Out}}
<pre>
ALPHABETA
alphabeta
</pre>
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Lowercase.png Lowercase] and [http://zoea.co.uk/examples/zv-rc/Uppercase.png Uppercase]
[[Category: String manipulation]]
[[Category: Encodings]]
|