Take the string     alphaBETA     and demonstrate how to convert it to:

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


Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.

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

Show any additional case conversion functions   (e.g. swapping case, capitalizing the first letter, etc.)   that may be included in the library of your language.


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



11l

Translation of: Python

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

Output:
ALPHABETA
alphabeta

360 Assembly

The first version uses a nice thing of EBCDIC coding, uppercase can be performed with a simple 'OR' with blank character (X'40'), in the same way lowercase can be performed with a 'AND' with character 191 (X'BF'). <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</lang>
Output:
alphaBETA
ALPHABETA
alphabeta

The second version uses the translate operation (TR opcode), but now EBCDIC coding with alphabetic in 3 sequences, makes things a bit longer to create translation tables. <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</lang>
Output:
alphaBETA
ALPHABETA
alphabeta

4D

<lang 4d>$string:="alphaBETA" $uppercase:=Uppercase($string) $lowercase:=Lowercase($string)</lang>

6502 Assembly

<lang> .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 </lang> Output:

Alpha, BETA, gamma, {[(<123@_>)]}.
ALPHA, BETA, GAMMA, {[(<123@_>)]}.
alpha, beta, gamma, {[(<123@_>)]}.

68000 Assembly

These algorithms work for any ASCII string. The implementation of actually printing the characters is left out, as it is not actually relevant to this task. <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</lang>

8080 Assembly

<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,'$'</lang>

Output:
alphaBETA
ALPHABETA
alphabeta

Action!

<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</lang>

Output:

Screenshot from Atari 8-bit computer

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

ActionScript

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

Ada

<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;</lang>

ALGOL 68

Translation of: C – Note: This specimen retains the original C coding style.
Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.

<lang algol68>#!/usr/local/bin/a68g --script #

  1. Demonstrate toupper and tolower for standard ALGOL 68

strings. This does not work for multibyte character sets. #

INT l2u = ABS "A" - ABS "a";

PROC to upper = (CHAR c)CHAR:

 (ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u ));

PROC to lower = (CHAR c)CHAR:

 (ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u ));
  1. Operators can be defined in ALGOL 68 #

OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper;

  1. upper-cases s in place #

PROC string to upper = (REF STRING s)VOID:

   FOR i FROM LWB s TO UPB s DO s[i] := to upper(s[i]) OD;
  1. 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))

)</lang> Output:

uppercase: ALPHABETA
lowercase: alphabeta

ALGOL W

<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.</lang>

Output:
ALPHABETA                               
alphabeta                               

Amazing Hopper

<lang Amazing Hopper>

  1. include <hopper.h>
  1. 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 </lang>

Output:
String to process: alphaBETA
UPPER: ALPHABETA
LOWER: alphabeta
SWAP CASE: ALPHAbeta
ARRAY UPPER: 
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA
ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA

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

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

APL

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

In the following example, puntuation is not covered. It is substituted by '*'. <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* </lang>

APL (Dyalog)

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

     ⎕C 'Πέτρος is using APL!'

πέτροσ is using apl!

     1 ⎕C 'Πέτρος is using APL!'

ΠΈΤΡΟΣ IS USING APL! </lang>

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

AppleScript

Translation of: JavaScript

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

<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</lang>

Output:

<lang AppleScript>{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}</lang>

Arbre

<lang arbre>main():

 uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io</lang>

Output:

ALPHABETA
alphabeta

Arturo

<lang rebol>str: "alphaBETA"

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

Output:
uppercase  : ALPHABETA 
lowercase  : alphabeta 
capitalize : AlphaBETA

AutoHotkey

<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"</lang>

AutoIt

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

Avail

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

AWK

<lang awk>BEGIN {

 a = "alphaBETA";
 print toupper(a), tolower(a)

}</lang>

Capitalize: <lang awk>BEGIN {

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

}</lang>

BASIC

Works with: QBasic

<lang qbasic>s$ = "alphaBETA" PRINT UCASE$(s$) PRINT LCASE$(s$)</lang>

Applesoft BASIC

<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$</lang>

BBC BASIC

<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$)</lang>

Output:

Original:   alphaBETA
Lower case: alphabeta
Upper case: ALPHABETA
Title case: AlphaBETA

Commodore BASIC

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

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


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

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

Code Example <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$</lang>

Output:
The original string is:                 
                                        
           alphaBETA                    
                                        
Uppercase: ALPHABETA                    
Lowercase: alphabeta                    
                                        
ready.                                  
█

IS-BASIC

<lang IS-BASIC>100 INPUT PROMPT "String: ":TX$ 110 PRINT "Lower case: ";LCASE$(TX$) 120 PRINT "Upper case: ";UCASE$(TX$)</lang>

Liberty BASIC

<lang lb> input$ ="alphaBETA"

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

end </lang>

PureBasic

<lang PureBasic>s$ = "alphaBETA" upper$ = UCase(s$) ;uppercase lower$ = LCase(s$) ;lowercase</lang>

Run BASIC

<lang runbasic>a$ ="alphaBETA"

print a$ '=> alphaBETA print upper$(a$) '=> ALPHABETA print lower$(a$) '=> alphabeta</lang>

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.

Visual Basic .NET

Works with: Visual Basic version 2008

<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()</lang>

<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</lang>

BCPL

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

$)</lang>

Output:
   String: alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta

Befunge

Works with: befungee

Converts to uppercase only; lowercase is done in a similar way so I chose not to add it. <lang Befunge>"ATEBahpla" > : #v_ 25* , @ >48*-v

                > :: "`"` \"{"\` * |    > , v
                                   >    ^
           ^                                <</lang>

Bracmat

The functions upp$ and low$ assume that strings are UTF-8 encoded, but if a string is not valid UTF-8, it is assumed the string is ISO-8859-1. Case conversion is not restricted to the Latin alphabet, but extends to all alphabets that have upper and lower case characters. <lang bracmat> "alphaBETA":?s & out$str$(upp$!s \n low$!s)</lang> Output:

ALPHABETA
alphabeta

Burlesque

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

C

The tolower and toupper functions are locale-aware. <lang c>/* Demonstrate toupper and tolower for

  standard C strings.
  This does not work for multibyte character sets. */
  1. include <ctype.h>
  2. include <stdio.h>

/* upper-cases s in place */ void str_toupper(char *s) {

   while(*s)
   {
       *s=toupper(*s);
       s++;
   }

}


/* lower-cases s in place */ void str_tolower(char *s) {

   while(*s)
   {
       *s=tolower(*s);
       s++;
   }

}

int main(int argc, char *argv[]) {

   char t[255]="alphaBETA";
   str_toupper(t);
   printf("uppercase: %s\n", t);
   str_tolower(t);
   printf("lowercase: %s\n", t);
   return 0;

}</lang>

C#

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

}</lang>

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

C++

Works with: g++ version 3.4.4 (cygming special)
Library: STL

This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.

<lang cpp>#include <algorithm>

  1. include <string>
  2. include <cctype>

/// \brief in-place convert string to upper case /// \return ref to transformed string void str_toupper(std::string &str) {

 std::transform(str.begin(), 
                str.end(), 
                str.begin(),
                (int(*)(int)) std::toupper);

}

/// \brief in-place convert string to lower case /// \return ref to transformed string void str_tolower(std::string &str) {

 std::transform(str.begin(), 
                str.end(), 
                str.begin(),
                (int(*)(int)) std::tolower);

}</lang>

Here is sample usage code:

<lang cpp>#include <iostream>

  1. include <string>

using namespace std; int main() {

 string foo("_upperCas3Me!!");
 str_toupper(foo);
 cout << foo << endl;
 str_tolower(foo);
 cout << foo << endl;
 return 0;

}</lang>

Clojure

<lang lisp>(def string "alphaBETA") (println (.toUpperCase string)) (println (.toLowerCase string))</lang>

CMake

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

-- Uppercase: ALPHABETA
-- Lowercase: alphabeta

COBOL

Standard-compliant Methods

<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
          .</lang>

Compiler Extensions

<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
          .</lang>

ColdFusion

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

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

Common Lisp

You can use the string-upcase function to perform upper casing:

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

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

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

Component Pascal

BlackBox Component Builder <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. </lang> Execute: ^Q AlphaBeta.Do
Output:

Uppercase:> ALPHABETA
Lowercase:> alphabeta

D

<lang d>void main() {

   import std.stdio, std.string;
   immutable s = "alphaBETA";
   s.toUpper.writeln;
   s.toLower.writeln;

}</lang>

Output:
ALPHABETA
alphabeta


DBL

<lang DBL> OPEN (1,O,'TT:') ;open video

STR="alphaBETA"

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

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

Delphi

<lang pascal>writeln(uppercase('alphaBETA')); writeln(lowercase('alphaBETA'));</lang>

DWScript

<lang delphi>PrintLn(UpperCase('alphaBETA')); PrintLn(LowerCase('alphaBETA'));</lang>

Dyalect

<lang dyalect>let str = "alphaBETA"

print("Lower case: ", str.Lower(), separator: "") print("Upper case: ", str.Upper(), separator: "") print("Capitalize: ", str.Capitalize(), separator: "")</lang>

E

<lang e>["alphaBETA".toUpperCase(), "alphaBETA".toLowerCase()]</lang>

EchoLisp

EchoLisp includes the usual case conversion functions and the randcase function : random case <lang scheme> (string-downcase "alphaBETA")

   → "alphabeta"

(string-upcase "alphaBETA")

   → "ALPHABETA"

(string-titlecase "alphaBETA")

   → "Alphabeta"

(string-randcase "alphaBETA")

   → "alphaBEtA"

(string-randcase "alphaBETA")

   → "AlPHaBeTA"

</lang>

ECL

<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);</lang>

Elena

ELENA 4.x: <lang elena>import system'culture;

public program() {

   string s1 := "alphaBETA";

   // Alternative 1
   console.writeLine(s1.lowerCase());
   console.writeLine(s1.upperCase());

   // Alternative 2
   console.writeLine(s1.toLower(currentLocale));
   console.writeLine(s1.toUpper(currentLocale));
   console.readChar()

}</lang>

Elixir

The String module provides the following functions: <lang elixir> String.downcase("alphaBETA")

  1. => alphabeta

String.upcase("alphaBETA")

  1. => ALPHABETA

String.capitalize("alphaBETA")

  1. => Alphabeta

</lang> As with most String functions in Elixir, these are fully compatible with Unicode. <lang elixir> String.downcase("αΒ")

  1. => αβ

String.upcase("αΒ")

  1. => ΑΒ

String.capitalize("αΒ")

  1. => Αβ

</lang>

Elm

<lang elm>import String exposing (toLower, toUpper)

s = "alphaBETA"

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

Erlang

<lang erlang>string:to_upper("alphaBETA"). string:to_lower("alphaBETA").</lang>

Excel

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

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

and in C1 :

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

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

<lang> alphaBETA alphabeta ALPHABETA </lang>

F#

<lang fsharp> let s = "alphaBETA" let upper = s.ToUpper() let lower = s.ToLower() </lang>

Factor

<lang factor>"alphaBETA" >lower  ! "alphabeta" "alphaBETA" >upper  ! "ALPHABETA" "alphaBETA" >title  ! "Alphabeta" "ß" >case-fold  ! "ss"</lang>

Falcon

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

Fantom

<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 </lang>

Forth

ANS Forth does not have words to convert case for either strings or characters. For known alpha-numeric ASCII characters, the following can be used:

: tolower ( C -- c ) 32 or ;
: toupper ( c -- C ) 32 invert and ;
: lower ( addr len -- ) over + swap  do i c@ tolower i c!  loop ;
: upper ( addr len -- ) over + swap  do i c@ toupper i c!  loop ;

If the character range is unknown, these definitions are better:

: tolower ( C -- c ) dup [char] A [char] Z 1+ within if 32 + then ;
: toupper ( c -- C ) dup [char] a [char] z 1+ within if 32 - then ;
Works with: Win32Forth version 4.2
create s ," alphaBETA"
s count type
s count 2dup upper type
s count 2dup lower type

Output:

alphaBETA
ALPHABETA
alphabeta

Fortran

Works with: Fortran version 90 and later

<lang fortran> program example

  implicit none
  
  character(9) :: teststring = "alphaBETA"
 
  call To_upper(teststring)
  write(*,*) teststring
  call To_lower(teststring)
  write(*,*) teststring
 
contains

  subroutine To_upper(str)
    character(*), intent(in out) :: str
    integer :: i
 
    do i = 1, len(str)
      select case(str(i:i))
        case("a":"z")
          str(i:i) = achar(iachar(str(i:i))-32)
      end select
    end do 
  end subroutine To_upper

  subroutine To_lower(str)
    character(*), intent(in out) :: str
    integer :: i
 
    do i = 1, len(str)
      select case(str(i:i))
        case("A":"Z")
          str(i:i) = achar(iachar(str(i:i))+32)
      end select
    end do  
  end subroutine To_Lower
end program example</lang>

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

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

For converting lower-case text to upper, the following will work both on an ASCII system and an EBCDIC system (or any other encodement), once it is compiled for that system: <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</lang>

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

       TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))
     END DO</lang>

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

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

<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 </lang>

FreeBASIC

<lang freebasic>' FB 1.05.0 Win64

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

Output:
ALPHABETA
alphabeta

Frink

<lang frink> a = "alphaBETA" println[lc[a]] println[uc[a]] </lang>

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

Produces:

IMBISS

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

<lang frink>lc[ uc["Imbiß"] ]</lang>

imbiss

FutureBasic

<lang futurebasic>window 1

CFStringRef s = @"alphaBETA"

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

HandleEvents</lang>

Output:

alphaBETA
ALPHABETA
alphabeta

Gambas

Click this link to run this code <lang gambas>Public Sub Main() Dim sString As String = "alphaBETA "

Print UCase(sString) Print LCase(sString)

End</lang> Output:

ALPHABETA 
alphabeta

GAP

<lang gap>LowercaseString("alphaBETA"); UppercaseString("alphaBETA");</lang>

GML

<lang GML>#define cases {

   x = 'alphaBETA';
   y = string_upper(x); // returns ALPHABETA
   z = string_lower(x); // returns alphabeta
   show_message(y);
   show_message(z);

}</lang>

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

}</lang> Output:

string:          alphaBETA  len: 9 runes
All upper case:  ALPHABETA
All lower case:  alphabeta
All title case:  ALPHABETA
Title words:     AlphaBETA
Swapping case:   ALPHAbeta

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

string:          DŽLjnj  len: 3 runes
All upper case:  DŽLJNJ
All lower case:  džljnj
All title case:  DžLjNj
Title words:     DžLjnj
Swapping case:   DžljNJ

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

Groovy

<lang groovy>def str = 'alphaBETA'

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

Output:

ALPHABETA
alphabeta

Haskell

<lang haskell>import Data.Char

s = "alphaBETA"

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

HicEst

<lang hicest>CHARACTER str = "alphaBETA" EDIT(Text=str, UpperCase=LEN(str)) EDIT(Text=str, LowerCase=LEN(str)) EDIT(Text=str, UpperCase=1) </lang>

Icon and Unicon

<lang Icon>procedure main()

   write(map("alphaBETA"))
   write(map("alphaBETA",&lcase,&ucase))

end</lang>

IDL

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

J

Use standard utilities: <lang j> toupper 'alphaBETA' ALPHABETA

  tolower 'alphaBETA'

alphabeta</lang>

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

For example: <lang j> upper 'alphaBETA' ALPHABETA

  lower 'alphaBETA'

alphabeta</lang>

Java

<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 "ß"</lang>

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

JavaScript

<lang javascript>alert( "alphaBETA".toUpperCase() ); alert( "alphaBETA".toLowerCase() );</lang>

Output:

ALPHABETA
alphabeta
Works with: NJS version 0.2.5

<lang javascript>var string = "alphaBETA"; var uppercase = string.toUpperCase(); var lowercase = string.toLowerCase();</lang>

jq

If your version of jq does not have ascii_downcase and ascii_upcase, then you might want to use their definitions: <lang jq># like ruby's downcase - only characters A to Z are affected def ascii_downcase:

 explode | map( if 65 <= . and . <= 90 then . + 32  else . end) | implode;
  1. 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;</lang>

Examples: <lang jq>"alphaBETA" | ascii_upcase

  1. => "ALPHABETA"

"alphaBETA" | ascii_downcase

  1. => "alphabeta"</lang>

Jsish

<lang javascript>var msg = "alphaBETA";

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

Julia

<lang julia>julia> uppercase("alphaBETA") "ALPHABETA"

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

K

<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]}'
 upper s

"ALPHABETA"

 lower s

"alphabeta" </lang>

Kotlin

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

}</lang>

Output:
ALPHABETA
alphabeta
AlphaBETA
alphaBETA

Lambdatalk

Lambdatalk can take benefit from CSS rules. <lang scheme> {span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta {span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA </lang>

Lasso

<lang Lasso>// Direct string return 'alphaBETA'->uppercase& 'alphaBETA'->lowercase&

// Assignment and manipulation of variables local(toupper = 'alphaBETA')

  1. toupper->uppercase
  2. toupper

local(tolower = 'alphaBETA')

  1. tolower->lowercase
  2. tolower</lang>

Lingo

Lingo has no case conversion functions, but for ASCII strings they can e.g. be implemented like this: <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</lang>

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

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

LiveCode

<lang LiveCode>put upper("alphaBETA") && lower("alphaBETA") ALPHABETA alphabeta</lang>

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

Lua

<lang Lua>str = "alphaBETA" print( string.upper(str) ) print( string.lower(str) )</lang>

M4

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

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

Maple

<lang Maple>str := "alphaBETA"; StringTools:-UpperCase(str); StringTools:-LowerCase(str);</lang> produces

     alphabeta
     ALPHABETA

Mathematica/Wolfram Language

<lang Mathematica>str="alphaBETA"; ToUpperCase[str] ToLowerCase[str]</lang>

Output:
ALPHABETA
alphabeta

MATLAB / Octave

<lang MATLAB>>> upper('alphaBETA')

ans =

ALPHABETA

>> lower('alphaBETA')

ans =

alphabeta</lang>

Maxima

<lang Maxima>supcase('alphaBETA'); sdowncase('alphaBETA');</lang>

MAXScript

Requires MAX 2008 <lang maxscript>str = "alphaBETA" print (toUpper str) print (toLower str)</lang>

Mercury

The functions to_upper/1, to_lower/1, capitalize_first/1 and uncapitalize_first/1 only affect unaccented Latin characters.

<lang>:- 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.</lang>

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

<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;</lang>

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

end</lang>

min

Works with: min version 0.19.3

<lang min>"alphaBETA" uppercase "alphaBETA" lowercase "alphaBETA" capitalize</lang>

MiniScript

<lang MiniScript>mixedString = "alphaBETA" print "Upper Case of " + mixedString + " is " + mixedString.upper print "Lower Case of " + mixedString + " is " + mixedString.lower</lang>

Output:
Upper Case of alphaBETA is ALPHABETA
Lower Case of alphaBETA is alphabeta

MIPS Assembly

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

Convert to upper case

<lang mips>ToUpper:

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

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

lb $t0,($a0) nop

beq $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</lang>

Convert to lower case

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

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

lb $t0,($a0) nop

beq $t0,ToLower_done 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

ToLower_done: jr ra nop</lang>

mIRC Scripting Language

<lang mirc>echo -ag $upper(alphaBETA) echo -ag $lower(alphaBETA)</lang>

Modula-3

<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.</lang> Output:

ALPHABETA
alphabeta

MUMPS

<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

</lang>

Output:

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

Nanoquery

<lang Nanoquery>string = "alphaBETA"

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

Nemerle

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

}</lang>

NetRexx

<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 </lang>

NewLISP

<lang NewLISP> (upper-case "alphaBETA") (lower-case "alphaBETA") </lang>

Nial

<lang nial>toupper 'alphaBETA' =ALPHABETA tolower 'alphaBETA' =alphabeta</lang>

Nim

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

<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.</lang>

Output:
alphaBETA_123 as upper case: ALPHABETA_123
alphaBETA_123 as lower case: alphabeta_123
alphaBETA_123 as capitalized: AlphaBETA_123
alphaBETA_123 as normal case: alphabeta123

Objeck

<lang objeck> string := "alphaBETA"; string->ToUpper()->PrintLine(); string->ToLower()->PrintLine(); </lang>

Objective-C

Works with: GNUstep
Works with: Cocoa

<lang objc>NSLog(@"%@", @"alphaBETA".uppercaseString); NSLog(@"%@", @"alphaBETA".lowercaseString);

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

OCaml

<lang ocaml>let () =

 let str = "alphaBETA" in
 print_endline (String.uppercase_ascii str); (* ALPHABETA *)
 print_endline (String.lowercase_ascii str); (* alphabeta *)
 print_endline (String.capitalize_ascii str); (* AlphaBETA *)
</lang>

Octave

<lang octave>s = "alphaBETA"; slc = tolower(s); suc = toupper(s); disp(slc); disp(suc);</lang>

Oforth

<lang Oforth>"alphaBETA" toUpper "alphaBETA" toLower</lang>

OpenEdge/Progress

<lang Progress (OpenEdge ABL)>caps("alphaBETA") lc("alphaBETA") </lang>

Oz

Convert to upper/lower-case: <lang oz>declare

 Str = "alphaBETA"

in

 {System.showInfo {Map Str Char.toUpper}}
 {System.showInfo {Map Str Char.toLower}}</lang>

Capitalize: <lang oz>declare

 [StringX] = {Link ['x-oz://system/String.ozf']}

in

 {System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"</lang>

Pascal

<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. </lang>

Demonstration:

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

Peloton

Iterating through the peerset <lang sgml><@ ENU$$$LSTPSTLITLIT>UPP| [<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@> <@ SAY&&&LIT>alphaBETA</@>

</@></lang>

Same code in padded-out, variable-length English dialect <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</#>

</#></lang>

Output.

[FLC] 410400001 Flip case (410400001)  [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting]
ALPHAbeta

[LOW] 410400002 Lower case (410400002)  [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting]
alphabeta

[PRP] 410400003 Proper Case (410400003)  [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting]
Alphabeta

[SNT] 410400004 Sentence case (410400004)  [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting]
Alphabeta

[UPP] 410400005 Upper case (410400005)  [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting]
ALPHABETA

Perl

Works with: Perl version 5.x

<lang perl>my $string = "alphaBETA"; print uc($string), "\n"; # => "ALPHABETA" print lc($string), "\n"; # => "alphabeta" $string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta

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

Also works in Perl 4 if the my is removed.

Phix

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

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

PHP

<lang php>$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta

echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz</lang>

Picat

<lang Picat>main =>

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

PicoLisp

<lang PicoLisp>(let Str "alphaBETA"

  (prinl (uppc Str))
  (prinl (lowc Str)) )</lang>

Pike

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

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

</lang>

Output:
Upper: "ALPHABETA"
Lower: "alphabeta"
Capitalize: "AlphaBETA"
Silly: "Foo Bar Gazonk"
Elite: "fo() 8ar 6azo|\\||<"

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

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

}</lang>

Output:
Upper: ἈΡΧῇ ß
Lower: ἀρχῇ ß

PL/I

<lang pli> declare s character (20) varying initial ('alphaBETA');

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

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

</lang>

PL/SQL

<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; </lang>

Plain English

<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.</lang>

Output:
ALPHABETA
alphabeta
Alphabeta

Pop11

<lang pop11>lvars str = 'alphaBETA'; lowertoupper(str) => uppertolower(str) =></lang>

Potion

<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</lang>

Powerbuilder

<lang powerbuilder>string ls_string ls_string = 'alphaBETA' ls_string = Upper(ls_string) ls_string = Lower(ls_string)</lang>

PowerShell

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

$lower, $upper, $title </lang>

Output:
alphabeta
ALPHABETA
Alphabeta

Python

<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"</lang>

string.capwords() allows the user to define word separators, and by default behaves slightly differently than title().

<lang python>print "foo's bar".title() # => "Foo'S Bar" print string.capwords("foo's bar") # => "Foo's Bar"</lang>

QB64

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

Optimized version:
CBTJD: 2020/03/13


  • String does not have to be defined with a specific length using DIM.
  • Addding the string identifier ($) to the variable is sufficient.
  • PRINT does not need empty quotes to print a blank line.
  • Semi-colons use less data than the concatenation (+) method.

<lang vb>s$ = "alphaBETA" PRINT "The original string: "; s$: PRINT PRINT "Converted to lowercase: "; LCASE$(s$) PRINT "Converted to uppercase: "; UCASE$(s$)</lang>


Quackery

<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</lang>
Output:
patrick, i don't think wumbo is a real word.
PATRICK, I DON'T THINK WUMBO IS A REAL WORD.


R

<lang R> str <- "alphaBETA"

toupper(str)
tolower(str)</lang>

Racket

<lang Racket>#lang racket (define example "alphaBETA")

(string-upcase example)

"ALPHABETA"

(string-downcase example)

"alphabeta"

(string-titlecase example)

"Alphabeta"</lang>

Raku

(formerly Perl 6) In Raku, case modification is implemented as builtin subroutine or method:

<lang perl6>my $word = "alpha BETA" ; say uc $word; # all uppercase (subroutine call) say $word.uc; # all uppercase (method call)

  1. 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 </lang> Output:

ALPHA BETA
alpha beta
Alpha BETA
Alpha beta
Alpha Beta

Raven

<lang raven>'alphaBETA' upper 'alhpaBETA' lower</lang>

REBOL

<lang REBOL>print ["Original: " original: "alphaBETA"] print ["Uppercase:" uppercase original] print ["Lowercase:" lowercase original]</lang>

Output:

Original:  alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta

Red

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

Retro

<lang Retro>'alphaBETA s:to-upper s:put 'alphaBETA s:to-lower s:put</lang>

REXX

with TRANSLATE BIF

The following code will execute correctly in   ASCII   and   EBCDIC. <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*/</lang>

with PARSE UPPER & PARSE LOWER statements

The following code will execute correctly in   ASCII   and   EBCDIC. <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.*/</lang>

with UPPER & LOWER BIFs

The following code will execute correctly in   ASCII   and   EBCDIC. <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).*/</lang>

with UPPER statement

The following code will execute correctly in   ASCII   and   EBCDIC. <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.*/</lang>

with capitalized words

The following code will execute correctly in   ASCII   and   EBCDIC. <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.        */</lang>

Some older REXXes don't have a   changestr   BIF, so one is included here   ───►   CHANGESTR.REX.

output:
alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh ayin pe tzadi qof resh shin  tav.
Alef Bet Gimel Dalet He Vav Zayin Het Tet Yod Kaf Lamed Mem Nun Samekh Ayin Pe Tzadi Qof Resh Shin  Tav.

Note:   there are many variant spellings of the Hebrew alphabet.

with case swap

The following code will execute correctly in   ASCII   and   EBCDIC. <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. */</lang>

output

alphaBETA
ALPHAbeta

version 2

<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 </lang>

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: <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 */  

</lang> Translation to lowercase is not similarly possible because of 'SS'->'ß' or -> 'ss' ??
Note: Recently an uppercase ß was introduced in Austria. I haven't used it yet.

Ring

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

Ruby

<lang ruby>"alphaBETA".downcase # => "alphabeta" "alphaBETA".upcase # => "ALPHABETA"

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

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

Works with: Ruby version 2.4

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

Rust

Works with: Rust version 1.3

<lang rust>fn main() {

   println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
   println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño

}</lang>

Scala

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

Scheme

<lang scheme>(define s "alphaBETA") (list->string (map char-upcase (string->list s))) (list->string (map char-downcase (string->list s)))</lang>

Using SRFI-13:

<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" </lang>

Sed

Piping through sed in bash:

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

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

GNU sed supports special sequences to change case: <lang bash>

  1. to uppercase

$ echo alphaBETA | sed 's/.*/\U&/' ALPHABETA

  1. to lowercase

$ echo alphaBETA | sed 's/.*/\L&/' alphabeta </lang>

Seed7

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

SenseTalk

<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 </lang>

Sidef

<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</lang>

Simula

<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;</lang>

Slate

<lang slate>'alphaBETA' toLowercase.

'alphaBETA' toUppercase.</lang>

Smalltalk

<lang smalltalk>'ALPHAbeta' asUppercase "->'ALPHABETA' " 'ALPHAbeta' asLowercase "-> 'alphabeta' "</lang>

Works with: Smalltalk/X

<lang smalltalk>'alphabeta' asUppercaseFirst "-> 'Alphabeta' "</lang> 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)

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

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.

<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</lang>

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

<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</lang>

Output:

alphaBETA
alphabeta
ALPHABETA
AlphaBETA
ALPHAbeta

SQL

Works with: MS SQL version 2005

<lang sql>declare @s varchar(10) set @s = 'alphaBETA' print upper(@s) print lower(@s)</lang>

SQL PL

Works with: Db2 LUW

With SQL only: <lang sql pl> values upper('alphaBETA'); values lower('alphaBETA'); values initcap('alphaBETA'); -- Within a SQL query. select upper('alphaBETA') from sysibm.sysdummy1; </lang> Output:

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

1        
---------
ALPHABETA

  1 record(s) selected.

db2 => values lower('alphaBETA');

1        
---------
alphabeta

  1 record(s) selected.

db2 => values initcap('alphaBETA');

1        
---------
Alphabeta

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

1        
---------
ALPHABETA

  1 record(s) selected.

Standard ML

<lang sml>val strupr = String.map Char.toUpper; val strlwr = String.map Char.toLower;</lang>

Test

- strupr "alphaBETA";
val it = "ALPHABETA" : string
- strlwr "alphaBETA";
val it = "alphabeta" : string

Stata

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

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

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

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

Swift

<lang swift>import Foundation

println("alphaBETA".uppercaseString) println("alphaBETA".lowercaseString) println("foO BAr".capitalizedString)</lang>

Output:
ALPHABETA
alphabeta
Foo Bar

Tcl

<lang tcl>set string alphaBETA

  1. three built-in case conversion commands

string toupper $string  ;# ==> ALPHABETA string tolower $string  ;# ==> alphabeta string totitle $string  ;# ==> Alphabeta

  1. 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

  1. 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</lang>

Toka

 needs ctype
 
 [ i 1 - ] is i
 [ string.getLength 0 [ dup i + c@ toupper over i + c! ] countedLoop ] is string.toUpper
 [ string.getLength 0 [ dup i + c@ tolower over i + c! ] countedLoop ] is string.toLower
 
 " alphaBETA" string.toUpper type cr
 " alphaBETA" string.toLower type cr

TorqueScript

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

Transd

<lang Scheme>#lang transd

MainModule: {

   _start: (λ 
       (with s "alphaBETA"
           (lout (toupper s))
           (lout (tolower s)))
   )

}</lang>

Output:
ALPHABETA
alphabeta

TUSCRIPT

<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 </lang> Output:

alphabeta
ALPHABETA
ALPHABETA

UNIX Shell

Works with: Bourne Shell

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

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

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

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

Z Shell

Works with: zsh

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

Ursa

<lang ursa>out (lower "alphaBETA") endl console out (upper "alphaBETA") endl console</lang>

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. <lang Ursala>#import std

to_upper = * -:~& ~=`A-~p letters to_lower = * -:~& ~=`A-~rlp letters

  1. show+

examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'></lang> output:

ALPHABETA
alphabeta

Vala

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

VBA

<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</lang>

Output:

ALPHABETA
alphabeta
Alphabeta

VBScript

<lang vbscript>Dim MyWord MyWord = UCase("alphaBETA") ' Returns "ALPHABETA" MyWord = LCase("alphaBETA") ' Returns "alphabeta"</lang>

Vedit macro language

<lang vedit>#1 = CP IT("alphaBETA") Case_Upper_Block(#1, CP) Case_Lower_Block(#1, CP)</lang>

Visual Basic

Works with: Visual Basic version VB6 Standard

<lang vb>Sub Main() Const TESTSTRING As String = "alphaBETA" Debug.Print "initial = " _

  & TESTSTRING

Debug.Print "uppercase = " _

  & UCase(TESTSTRING)

Debug.Print "lowercase = " _

  & LCase(TESTSTRING)

Debug.Print "first letter capitalized = " _

  & StrConv(TESTSTRING, vbProperCase)

Debug.Print "length (in characters) = " _

  & CStr(Len(TESTSTRING))

Debug.Print "length (in bytes) = " _

  & CStr(LenB(TESTSTRING))

Debug.Print "reversed = " _

  & StrReverse(TESTSTRING)

Debug.Print "first position of letter A (case-sensitive) = " _

  & InStr(1, TESTSTRING, "A", vbBinaryCompare)

Debug.Print "first position of letter A (case-insensitive) = " _

  & InStr(1, TESTSTRING, "A", vbTextCompare)

Debug.Print "concatenated with '123' = " _

  & TESTSTRING & "123"

End Sub</lang>

Output:
initial   =                                      alphaBETA
uppercase =                                      ALPHABETA
lowercase =                                      alphabeta
first letter capitalized =                       Alphabeta
length (in characters) =                         9
length (in bytes) =                              18
reversed =                                       ATEBahpla
first position of letter A (case-sensitive) =    9
first position of letter A (case-insensitive) =  1
concatenated with '123' =                        alphaBETA123

Vlang

Translation of: go

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

}</lang> Output:

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

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

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

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

Wren

Library: Wren-str

<lang ecmascript>import "/str" for Str

var s = "alphaBETA" System.print(Str.upper(s)) System.print(Str.lower(s))</lang>

Output:
ALPHABETA
alphabeta

XPL0

<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); ]</lang>

Output:

ALPHABETA
alphabeta

Z80 Assembly

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

<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

</lang>
Output:
ALPHABETA
alphabeta
ALPHAbeta

zkl

<lang zkl>s:="alphaBETA"; s.toLower(); //--> "alphabeta" s.toUpper(); //--> "ALPHABETA"</lang>

Zig

<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://github.com/jecolon/zigstr

}</lang>

Zoea

<lang Zoea> program: uppercase

 input: 'FOObar'
 output: 'FOOBAR'

program: lowercase

 input: 'FOObar'
 output: 'foobar'

</lang>

Output:
ALPHABETA
alphabeta

Zoea Visual

Lowercase and Uppercase