String case: Difference between revisions
Added Ed |
|||
(394 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{task| |
{{task|String manipulation}} |
||
;Task: |
|||
Take the string "alphaBETA", and demonstrate how to convert it to UPPER-CASE and lower-case. |
|||
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}}== |
=={{header|4D}}== |
||
<syntaxhighlight lang="4d">$string:="alphaBETA" |
|||
$uppercase:=Uppercase($string) |
|||
$lowercase:=Lowercase($string)</syntaxhighlight> |
|||
=={{header|6502 Assembly}}== |
|||
$string:="alphaBETA" |
|||
$uppercase:=Uppercase($string) |
|||
<syntaxhighlight lang="text"> .lf case6502.lst |
|||
$lowercase:=Lowercase($string) |
|||
.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|ActionScript}}== |
||
<syntaxhighlight lang="actionscript">var string:String = 'alphaBETA'; |
|||
var upper:String = string.toUpperCase(); |
|||
var lower:String = string.toLowerCase();</syntaxhighlight> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
<syntaxhighlight lang="ada">with Ada.Characters.Handling, Ada.Text_IO; |
|||
use Ada.Characters.Handling, Ada.Text_IO; |
|||
<lang ada> |
|||
with Ada.Characters.Handling; use Ada.Characters.Handling; |
|||
with Ada.Text_Io; use Ada.Text_Io; |
|||
procedure Upper_Case_String is |
procedure Upper_Case_String is |
||
S : String := "alphaBETA"; |
S : constant String := "alphaBETA"; |
||
begin |
begin |
||
Put_Line(To_Upper(S)); |
Put_Line (To_Upper (S)); |
||
Put_Line(To_Lower(S)); |
Put_Line (To_Lower (S)); |
||
end Upper_Case_String; |
end Upper_Case_String;</syntaxhighlight> |
||
</lang> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{trans|C|Note: This specimen retains the original [[#C|C]] coding style.}} |
|||
# Demonstrate toupper and tolower for standard ALGOL 68 |
|||
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}} |
|||
strings. This does not work for multibyte character sets. # |
|||
{{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''.}} |
|||
PROC to upper = ( CHAR c )CHAR: |
|||
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script # |
|||
( |
|||
IF ABS "a" <= ABS c & ABS c <= ABS "z" THEN |
|||
# Demonstrate toupper and tolower for standard ALGOL 68 |
|||
REPR ( ABS c - ABS "a" + ABS "A" ) |
|||
strings. This does not work for multibyte character sets. # |
|||
ELSE |
|||
c |
|||
INT l2u = ABS "A" - ABS "a"; |
|||
FI |
|||
); |
|||
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: |
|||
( |
|||
PROC to lower = (CHAR c)CHAR: |
|||
IF ABS "A" <= ABS c & ABS c <= ABS "Z" THEN |
|||
(ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u )); |
|||
ELSE |
|||
# Operators can be defined in ALGOL 68 # |
|||
c |
|||
OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper; |
|||
FI |
|||
); |
|||
# 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; |
|||
PROC str to upper = (REF STRING s)VOID : |
|||
( |
|||
# lower-cases s in place # |
|||
FOR i FROM LWB s TO UPB s DO |
|||
PROC string to lower = (REF STRING s)VOID: |
|||
s[i] := toupper(s[i]) |
|||
FOR i FROM LWB s TO UPB s DO s[i] := to lower(s[i]) OD; |
|||
OD |
|||
); |
|||
main: ( |
|||
STRING t := "alphaBETA"; |
|||
# lower-cases s in place # |
|||
string to upper(t); |
|||
PROC str to lower = (REF STRING s)VOID : |
|||
printf(($"uppercase: "gl$, t)); |
|||
( |
|||
string to lower(t); |
|||
FOR i FROM LWB s TO UPB s DO |
|||
printf(($"lowercase: "gl$, t)) |
|||
s[i] := tolower(s[i]) |
|||
)</syntaxhighlight> |
|||
OD |
|||
Output: |
|||
); |
|||
<pre> |
|||
uppercase: ALPHABETA |
|||
main: ( |
|||
lowercase: alphabeta |
|||
STRING t := "alphaBETA"; |
|||
</pre> |
|||
str to upper(t); |
|||
printf(($"uppercase: "gl$, t)); |
|||
=={{header|ALGOL W}}== |
|||
str to lower(t); |
|||
<syntaxhighlight lang="algolw">begin |
|||
printf(($"lowercase: "gl$, t)) |
|||
% 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}}== |
=={{header|APL}}== |
||
Line 86: | Line 639: | ||
(A,⎕AV)[(a,⎕AV)⍳'alphaBETA'] |
(A,⎕AV)[(a,⎕AV)⍳'alphaBETA'] |
||
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}}== |
=={{header|BASIC}}== |
||
{{works with| |
{{works with|QBasic}} |
||
<syntaxhighlight lang="qbasic">s$ = "alphaBETA" |
|||
PRINT UCASE$(s$) |
|||
PRINT LCASE$(s$)</syntaxhighlight> |
|||
=={{header| |
==={{header|Applesoft BASIC}}=== |
||
<syntaxhighlight lang="applesoftbasic">S$ = "alphaBETA" |
|||
{{works with|gcc| 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)}} |
|||
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$ |
|||
{{libheader|libc}} |
|||
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> |
|||
<lang c> |
|||
// Demonstrate toupper and tolower for |
|||
==={{header|BASIC256}}=== |
|||
// standard C strings. |
|||
<syntaxhighlight lang="freebasic">s$ = "alphaBETA" |
|||
// This does not work for multibyte character sets. |
|||
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 <ctype.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
/ |
/* upper-cases s in place */ |
||
void str_toupper(char *s) |
void str_toupper(char *s) |
||
{ |
{ |
||
Line 116: | Line 1,259: | ||
/ |
/* lower-cases s in place */ |
||
void str_tolower(char *s) |
void str_tolower(char *s) |
||
{ |
{ |
||
Line 134: | Line 1,277: | ||
printf("lowercase: %s\n", t); |
printf("lowercase: %s\n", t); |
||
return 0; |
return 0; |
||
}</syntaxhighlight> |
|||
} |
|||
</lang> |
|||
=={{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++}}== |
=={{header|C++}}== |
||
Line 144: | Line 1,316: | ||
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator. |
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator. |
||
<syntaxhighlight lang="cpp">#include <algorithm> |
|||
<lang cpp> |
|||
#include <algorithm> |
|||
#include <string> |
#include <string> |
||
#include <cctype> |
#include <cctype> |
||
Line 165: | Line 1,336: | ||
str.begin(), |
str.begin(), |
||
(int(*)(int)) std::tolower); |
(int(*)(int)) std::tolower); |
||
}</syntaxhighlight> |
|||
} |
|||
</lang> |
|||
Here is sample usage code: |
Here is sample usage code: |
||
<syntaxhighlight lang="cpp">#include <iostream> |
|||
<lang cpp> |
|||
#include <iostream> |
|||
#include <string> |
#include <string> |
||
Line 182: | Line 1,351: | ||
cout << foo << endl; |
cout << foo << endl; |
||
return 0; |
return 0; |
||
}</syntaxhighlight> |
|||
} |
|||
</lang> |
|||
=={{header| |
=={{header|Clojure}}== |
||
<syntaxhighlight lang="lisp">(def string "alphaBETA") |
|||
(println (.toUpperCase string)) |
|||
(println (.toLowerCase string))</syntaxhighlight> |
|||
=={{header|CMake}}== |
|||
<lang csharp> |
|||
<syntaxhighlight lang="cmake">string(TOUPPER alphaBETA s) |
|||
string array = "alphaBETA"; |
|||
message(STATUS "Uppercase: ${s}") |
|||
System.Console.WriteLine(array.ToUpper()); |
|||
string(TOLOWER alphaBETA s) |
|||
System.Console.WriteLine(array.ToLower()); |
|||
message(STATUS "Lowercase: ${s}")</syntaxhighlight> |
|||
</lang> |
|||
<pre>-- Uppercase: ALPHABETA |
|||
=={{header|Clojure}}== |
|||
-- Lowercase: alphabeta</pre> |
|||
(def string "alphaBETA) |
|||
(println (. string toUpperCase)) |
|||
=={{header|COBOL}}== |
|||
(println (. string toLowerCase)) |
|||
===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}}== |
=={{header|ColdFusion}}== |
||
converting a string literal |
converting a string literal |
||
<syntaxhighlight lang="coldfusion"><cfset upper = UCase("alphaBETA")> |
|||
<cfset lower = LCase("alphaBETA")></syntaxhighlight> |
|||
converting the value of a variable |
converting the value of a variable |
||
<syntaxhighlight lang="coldfusion"><cfset string = "alphaBETA"> |
|||
<cfset upper = UCase(string)> |
|||
<cfset lower = LCase(string)></syntaxhighlight> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
You can use the ''string-upcase'' function to perform upper casing: |
You can use the ''string-upcase'' function to perform upper casing: |
||
<syntaxhighlight lang="lisp">CL-USER> (string-upcase "alphaBETA") |
|||
"ALPHABETA"</syntaxhighlight> |
|||
and you can do lower casing by using ''string-downcase'': |
and you can do lower casing by using ''string-downcase'': |
||
<syntaxhighlight lang="lisp">CL-USER> (string-downcase "alphaBETA") |
|||
"alphabeta"</syntaxhighlight> |
|||
=={{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}}== |
=={{header|D}}== |
||
<syntaxhighlight lang="d">void main() { |
|||
<lang d> |
|||
import std.stdio, std.string; |
|||
import tango.text.Unicode : toUpper, toLower; |
|||
import tango.io.Stdout; |
|||
immutable s = "alphaBETA"; |
|||
void main() { |
|||
s.toUpper.writeln; |
|||
auto str = "alphaBETA"; |
|||
s.toLower.writeln; |
|||
}</syntaxhighlight> |
|||
Stdout(str.toLower()).newline; |
|||
{{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); |
|||
} |
} |
||
</lang> |
|||
void main() { |
|||
=={{header|Delphi|Turbo Pascal|Object Pascal|Standard Pascal}}== |
|||
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}}== |
|||
writeln(uppercase('alphaBETA')); |
|||
<syntaxhighlight lang="dbl"> |
|||
writeln(lowercase('alphaBETA')); |
|||
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}}== |
=={{header|E}}== |
||
<syntaxhighlight lang="e">["alphaBETA".toUpperCase(), |
|||
"alphaBETA".toLowerCase()]</syntaxhighlight> |
|||
=={{header|EasyLang}}== |
|||
["alphaBETA".toUpperCase(), |
|||
EasyLang does not have string case functions. The functions provided below only work with ASCII. |
|||
"alphaBETA".toLowerCase()] |
|||
<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}}== |
=={{header|Factor}}== |
||
<syntaxhighlight lang="factor">"alphaBETA" >lower ! "alphabeta" |
|||
"alphaBETA" >upper ! "ALPHABETA" |
|||
"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}}== |
=={{header|Forth}}== |
||
Line 272: | Line 1,844: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran"> program example |
||
program example |
|||
implicit none |
implicit none |
||
Line 310: | Line 1,881: | ||
end subroutine To_Lower |
end subroutine To_Lower |
||
end program example |
end program example</syntaxhighlight> |
||
</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 <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}}== |
=={{header|Haskell}}== |
||
<syntaxhighlight lang="haskell">import Data.Char |
|||
s = "alphaBETA" |
|||
import Data.Char |
|||
s = "alphaBETA" |
|||
lower = map toLower s |
|||
upper = map toUpper s |
|||
lower = map toLower s |
|||
=={{header|IDL}}== |
|||
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" |
str = "alphaBETA" |
||
print, str |
print, str |
||
Line 330: | Line 2,170: | ||
=={{header|J}}== |
=={{header|J}}== |
||
Use standard utilities: |
|||
<syntaxhighlight lang="j"> toupper 'alphaBETA' |
|||
ALPHABETA |
|||
tolower 'alphaBETA' |
|||
alphabeta</syntaxhighlight> |
|||
or alternative definitions: |
|||
upper=: (a.,~a.{~65+i.26) {~ (a.,~a.{~97+i.26) i. ] |
|||
<syntaxhighlight lang="j">upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.) |
|||
lower=: (a.,~a.{~97+i.26) {~ (a.,~a.{~65+i.26) i. ] |
|||
lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)</syntaxhighlight> |
|||
For example: |
For example: |
||
<syntaxhighlight lang="j"> upper 'alphaBETA' |
|||
ALPHABETA |
|||
upper 'alphaBETA' |
|||
lower 'alphaBETA' |
|||
ALPHABETA |
|||
alphabeta</syntaxhighlight> |
|||
lower 'alphaBETA' |
|||
alphabeta |
|||
=={{header|Java}}== |
=={{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> |
|||
< |
<br /> |
||
Alternately |
|||
String str = "alphaBETA"; |
|||
<syntaxhighlight lang="java">String str = "alphaBETA"; |
|||
System.out.println(str.toUpperCase()); |
System.out.println(str.toUpperCase()); |
||
System.out.println(str.toLowerCase()); |
System.out.println(str.toLowerCase()); |
||
//Also works with non-English characters with no modification |
|||
</lang> |
|||
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>. |
You could also easily create a <tt>swapCase</tt> method using <tt>Character.isLowerCase()</tt>, <tt>Character.isUpperCase()</tt>, and <tt>Character.isLetter()</tt>. |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<syntaxhighlight lang="javascript">alert( "alphaBETA".toUpperCase() ); |
|||
<lang javascript> |
|||
alert( "alphaBETA". |
alert( "alphaBETA".toLowerCase() );</syntaxhighlight> |
||
alert( "alphaBETA".toLowerCase() ); |
|||
</lang> |
|||
Output: |
Output: |
||
Line 361: | Line 2,216: | ||
{{works with|NJS| 0.2.5}} |
{{works with|NJS| 0.2.5}} |
||
< |
<syntaxhighlight lang="javascript">var string = "alphaBETA"; |
||
var string = "alphaBETA"; |
|||
var uppercase = string.toUpperCase(); |
var uppercase = string.toUpperCase(); |
||
var lowercase = string.toLowerCase(); |
var lowercase = string.toLowerCase();</syntaxhighlight> |
||
</lang> |
|||
=={{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}}== |
=={{header|Logo}}== |
||
print uppercase "alphaBETA ; ALPHABETA |
print uppercase "alphaBETA ; ALPHABETA |
||
print lowercase "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}}== |
=={{header|MAXScript}}== |
||
Requires MAX 2008 |
Requires MAX 2008 |
||
< |
<syntaxhighlight lang="maxscript">str = "alphaBETA" |
||
print (toUpper str) |
print (toUpper str) |
||
print (toLower 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> |
</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|Nial}}== |
||
<syntaxhighlight lang="nial">toupper 'alphaBETA' |
|||
=ALPHABETA |
|||
tolower 'alphaBETA' |
|||
=alphabeta</syntaxhighlight> |
|||
=={{header| |
=={{header|Nim}}== |
||
In the following example, we use the ASCII version of the procedures to convert to lower case, to convert to upper case or to capitalize. In module “unicode” there exists also three procedures "toLower", "toUpper" and "capitalize" which can do the same thing for UTF-8 encoded strings. |
|||
<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|GNUstep}} |
||
{{works with|Cocoa}} |
{{works with|Cocoa}} |
||
<syntaxhighlight lang="objc">NSLog(@"%@", @"alphaBETA".uppercaseString); |
|||
NSLog(@"%@", @"alphaBETA".lowercaseString); |
|||
NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"</syntaxhighlight> |
|||
<lang objc> |
|||
NSLog([@"alphaBETA" uppercaseString]); |
|||
NSLog([@"alphaBETA" lowercaseString]); |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let _ = |
|||
let str = "alphaBETA" in |
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> |
|||
;;</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}}== |
=={{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> |
<pre> |
||
Original string : alphaBETA |
|||
%% to compile : ozc -x <file> |
|||
Reversed case : ALPHAbeta |
|||
functor |
|||
Upper case : ALPHABETA |
|||
import Open Application |
|||
Lower case : alphabeta |
|||
define |
|||
</pre> |
|||
Stdout = {New Open.file init(name:stdout)} |
|||
=={{header|PascalABC.NET}}== |
|||
proc{PrintLn Msg} {Stdout write(vs:Msg#'\n')} end |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
var s := 'exAmpLe sTrinG'; |
|||
s.ToLower.Println; |
|||
s.ToUpper.Println; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
example string |
|||
EXAMPLE STRING |
|||
</pre> |
|||
fun{SwapCase Ch} |
|||
if{Char.isUpper Ch} then {Char.toLower Ch} |
|||
elseif {Char.isLower Ch} then {Char.toUpper Ch} |
|||
else Ch end |
|||
end |
|||
fun{StrCase CharCaseFunc InStr} |
|||
{Map InStr CharCaseFunc} |
|||
end |
|||
=={{header|Peloton}}== |
|||
{PrintLn {StrCase Char.toUpper "alphaBETA"}} |
|||
Iterating through the peerset |
|||
{PrintLn {StrCase Char.toLower "alphaBETA"}} |
|||
<syntaxhighlight lang="sgml"><@ ENU$$$LSTPSTLITLIT>UPP| |
|||
{PrintLn {StrCase SwapCase "alphaBETA"}} |
|||
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@> |
|||
<@ SAY&&&LIT>alphaBETA</@> |
|||
{Application.exit 0} |
|||
end</pre> |
|||
=={{header|OpenEdge/Progress}}== |
|||
</@></syntaxhighlight> |
|||
caps("alphaBETA") |
|||
lc("alphaBETA") |
|||
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}}== |
=={{header|Perl}}== |
||
{{works with|Perl|5.x}} |
{{works with|Perl|5.x}} |
||
<syntaxhighlight lang="perl">my $string = "alphaBETA"; |
|||
<lang perl> |
|||
print uc($string), "\n"; # => "ALPHABETA" |
|||
print |
print lc($string), "\n"; # => "alphabeta" |
||
$string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta |
|||
print lc($string), "\n"; |
|||
</lang> |
|||
print ucfirst($string), "\n"; # => "AlphaBETA" |
|||
print lcfirst("FOObar"), "\n"; # => "fOObar"</syntaxhighlight> |
|||
Also works in Perl 4 if the '''my''' is removed. |
Also works in Perl 4 if the '''my''' is removed. |
||
=={{header|Phix}}== |
|||
{{works with |Perl|6}} |
|||
{{libheader|Phix/basics}} |
|||
<lang perl> |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
my $string = "alphaBETA"; |
|||
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"alphaBETA"</span> |
|||
say $string.uc |
|||
<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> |
|||
say $string.lc |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
|||
</lang> |
|||
<!--</syntaxhighlight>--> |
|||
There is also a bespoke convertCase function in demo\Edix\Edix.exw which accepts five operators: LOWER, UPPER, CAPITALISE, SENTENCE, and INVERT, which is obviously not part of the language, and a bit too long, messy, ugly, and unedifying, to bother reproducing here. |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
<syntaxhighlight lang="php">$str = "alphaBETA"; |
|||
<lang php> |
|||
echo strtoupper($str), "\n"; // ALPHABETA |
|||
$str = "alphaBETA"; |
|||
echo |
echo strtolower($str), "\n"; // alphabeta |
||
echo strtolower($str), "\n"; |
|||
echo ucfirst($str), "\n"; // AlphaBETA |
|||
</lang> |
|||
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}}== |
=={{header|Pop11}}== |
||
<syntaxhighlight lang="pop11">lvars str = 'alphaBETA'; |
|||
lowertoupper(str) => |
|||
uppertolower(str) =></syntaxhighlight> |
|||
=={{header|Potion}}== |
|||
lvars str = 'alphaBETA'; |
|||
<syntaxhighlight lang="potion">lowercase = (str) : |
|||
lowertoupper(str) => |
|||
low = ("") |
|||
uppertolower(str) => |
|||
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}}== |
=={{header|Python}}== |
||
<syntaxhighlight lang="python">s = "alphaBETA" |
|||
<lang python> |
|||
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" |
s = "alphaBETA" |
||
PRINT "The original string: " + s |
|||
print s.upper() |
|||
PRINT "" |
|||
print s.lower() |
|||
PRINT "Translated to lowercase: " + LCASE$(s) |
|||
print s.swapcase() |
|||
PRINT "Translated to uppercase: " + UCASE$(s)</syntaxhighlight> |
|||
</lang> |
|||
'''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}}== |
=={{header|Raven}}== |
||
<syntaxhighlight lang="raven">'alphaBETA' upper |
|||
'alhpaBETA' lower</syntaxhighlight> |
|||
=={{header|REBOL}}== |
|||
'alphaBETA' upper |
|||
<syntaxhighlight lang="rebol">print ["Original: " original: "alphaBETA"] |
|||
'alhpaBETA' lower |
|||
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}}== |
=={{header|Ruby}}== |
||
<syntaxhighlight lang="ruby">"alphaBETA".downcase # => "alphabeta" |
|||
{{works with|Ruby| 1.8}} |
|||
<lang ruby> |
|||
"alphaBETA".downcase # => "alphabeta" |
|||
"alphaBETA".upcase # => "ALPHABETA" |
"alphaBETA".upcase # => "ALPHABETA" |
||
"alphaBETA".swapcase # => "ALPHAbeta" |
"alphaBETA".swapcase # => "ALPHAbeta" |
||
"alphaBETA".capitalize # => "Alphabeta"</syntaxhighlight> |
|||
</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) |
|||
=={{header|Scheme}}== |
|||
{{works with|Ruby| 2.4}} |
|||
<syntaxhighlight lang="ruby">'ĥåçýджк'.upcase # => "ĤÅÇÝДЖК"</syntaxhighlight> |
|||
=={{header|Rust}}== |
|||
<lang scheme> |
|||
{{works with|Rust| 1.3}} |
|||
(define s "alphaBETA") |
|||
<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-upcase (string->list s))) |
||
(list->string (map char-downcase (string->list s))) |
(list->string (map char-downcase (string->list s)))</syntaxhighlight> |
||
</lang> |
|||
Using SRFI-13: |
|||
=={{header|Seed7}}== |
|||
<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(upper("alphaBETA")); |
||
writeln(lower("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}}== |
=={{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}}== |
|||
'ALPHAbeta' asUppercase. |
|||
'ALPHAbeta' asLowercase. |
|||
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. |
|||
=={{header|Standard ML}}== |
|||
<syntaxhighlight lang="snobol4"> define('uc(str)') :(uc_end) |
|||
uc uc = replace(str,&lcase,&ucase) :(return) |
|||
uc_end |
|||
define('lc(str)') :(lc_end) |
|||
val strupr = String.map Char.toUpper; |
|||
lc lc = replace(str,&ucase,&lcase) :(return) |
|||
val strlwr = String.map Char.toLower; |
|||
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 |
Test |
||
Line 515: | Line 3,742: | ||
<i>val it = "alphabeta" : string</i> |
<i>val it = "alphabeta" : string</i> |
||
=={{header| |
=={{header|Stata}}== |
||
{{works with|MS SQL| 2005}} |
|||
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. |
|||
declare @s varchar(10) |
|||
set @s = 'alphaBETA' |
|||
<syntaxhighlight lang="stata">. scalar s="alphaBETA" |
|||
print upper(@s) |
|||
. di strupper(s) |
|||
print lower(@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}}== |
=={{header|Tcl}}== |
||
<syntaxhighlight lang="tcl">set string alphaBETA |
|||
# three built-in case conversion commands |
|||
set string alphaBETA |
|||
string toupper $string ;# ==> ALPHABETA |
|||
string tolower $string ;# ==> alphabeta |
|||
# ==> ALPHABETA |
|||
string totitle $string ;# ==> Alphabeta |
|||
#==> 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 |
|||
=={{header|Toka}}== |
|||
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 |
needs ctype |
||
Line 542: | Line 3,816: | ||
" alphaBETA" string.toLower type cr |
" alphaBETA" string.toLower type cr |
||
=={{header| |
=={{header|TorqueScript}}== |
||
$string = "alphaBETA"; |
|||
echo "alphaBETA" |tr '[a-z]' '[A-Z]' |
|||
$upperCase = strUpr($string); |
|||
echo "alphaBETA" |tr '[A-Z]' '[a-z]' |
|||
$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}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vbscript">Dim MyWord |
|||
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA" |
|||
MyWord = LCase("alphaBETA") ' Returns "alphabeta"</syntaxhighlight> |
|||
=={{header|Vedit macro language}}== |
|||
Dim MyWord |
|||
<syntaxhighlight lang="vedit">#1 = CP |
|||
MyWord = UCase("Hello World") ' Returns "HELLO WORLD". |
|||
IT("alphaBETA") |
|||
MyWord = LCase("Hello World") ' Returns "hello world". |
|||
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(){ |
|||
=={{header|Visual Basic .NET}}== |
|||
show('alphaBETA') |
|||
Works with Visual Basic 2008. |
|||
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 |
|||
' Define 's' |
|||
All upper case: ALPHA BETA |
|||
Dim s AS String = "alphaBETA" |
|||
All lower case: alpha beta |
|||
Title words: Alpha BETA |
|||
' Change 's' to Upper Case. |
|||
s = s.ToUpper() |
|||
string: DŽLjnj len: 6 |
|||
All upper case: DŽLjnj |
|||
' Change 's' to Lower Case. |
|||
All lower case: DŽLjnj |
|||
s = s.ToLower() |
|||
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]] |
Latest revision as of 22:57, 5 July 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Take the string alphaBETA and demonstrate how to convert it to:
- upper-case and
- lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.
- Metrics
- Counting
- Word frequency
- Letter frequency
- Jewels and stones
- I before E except after C
- Bioinformatics/base count
- Count occurrences of a substring
- Count how many vowels and consonants occur in a string
- Remove/replace
- XXXX redacted
- Conjugate a Latin verb
- Remove vowels from a string
- String interpolation (included)
- Strip block comments
- Strip comments from a string
- Strip a set of characters from a string
- Strip whitespace from a string -- top and tail
- Strip control codes and extended characters from a string
- Anagrams/Derangements/shuffling
- Word wheel
- ABC problem
- Sattolo cycle
- Knuth shuffle
- Ordered words
- Superpermutation minimisation
- Textonyms (using a phone text pad)
- Anagrams
- Anagrams/Deranged anagrams
- Permutations/Derangements
- Find/Search/Determine
- ABC words
- Odd words
- Word ladder
- Semordnilap
- Word search
- Wordiff (game)
- String matching
- Tea cup rim text
- Alternade words
- Changeable words
- State name puzzle
- String comparison
- Unique characters
- Unique characters in each string
- Extract file extension
- Levenshtein distance
- Palindrome detection
- Common list elements
- Longest common suffix
- Longest common prefix
- Compare a list of strings
- Longest common substring
- Find common directory path
- Words from neighbour ones
- Change e letters to i in words
- Non-continuous subsequences
- Longest common subsequence
- Longest palindromic substrings
- Longest increasing subsequence
- Words containing "the" substring
- Sum of the digits of n is substring of n
- Determine if a string is numeric
- Determine if a string is collapsible
- Determine if a string is squeezable
- Determine if a string has all unique characters
- Determine if a string has all the same characters
- Longest substrings without repeating characters
- Find words which contains all the vowels
- Find words which contain the most consonants
- Find words which contains more than 3 vowels
- Find words whose first and last three letters are equal
- Find words with alternating vowels and consonants
- Formatting
- Substring
- Rep-string
- Word wrap
- String case
- Align columns
- Literals/String
- Repeat a string
- Brace expansion
- Brace expansion using ranges
- Reverse a string
- Phrase reversals
- Comma quibbling
- Special characters
- String concatenation
- Substring/Top and tail
- Commatizing numbers
- Reverse words in a string
- Suffixation of decimal numbers
- Long literals, with continuations
- Numerical and alphabetical suffixes
- Abbreviations, easy
- Abbreviations, simple
- Abbreviations, automatic
- Song lyrics/poems/Mad Libs/phrases
- Mad Libs
- Magic 8-ball
- 99 bottles of beer
- The Name Game (a song)
- The Old lady swallowed a fly
- The Twelve Days of Christmas
- Tokenize
- Text between
- Tokenize a string
- Word break problem
- Tokenize a string with escaping
- Split a character string based on change of character
- Sequences
11l
V s = ‘alphaBETA’
print(s.uppercase())
print(s.lowercase())
- Output:
ALPHABETA alphabeta
360 Assembly
The first version uses a nice thing of EBCDIC coding, uppercase can be performed with a simple 'OR' with blank character (X'40'), in the same way lowercase can be performed with a 'AND' with character 191 (X'BF').
UCASE CSECT
USING UCASE,R15
MVC UC,PG
MVC LC,PG
OC UC,=16C' ' or X'40' uppercase
NC LC,=16X'BF' and X'BF' lowercase
XPRNT PG,L'PG print original
XPRNT UC,L'UC print uc
XPRNT LC,L'LC print lc
BR R14
PG DC CL9'alphaBETA'
UC DS CL(L'PG)
LC DS CL(L'PG)
YREGS
END UCASE
- Output:
alphaBETA ALPHABETA alphabeta
The second version uses the translate operation (TR opcode), but now EBCDIC coding with alphabetic in 3 sequences, makes things a bit longer to create translation tables.
UCASE CSECT
USING UCASE,R15
MVC UC,PG
MVC LC,PG
TR UC,TABLEU TR uppercase
TR LC,TABLEL TR lowercase
XPRNT PG,L'PG print original
XPRNT UC,L'UC print uc
XPRNT LC,L'LC print lc
BR R14
PG DC CL9'alphaBETA'
UC DS CL(L'PG)
LC DS CL(L'PG)
TABLEU DC 256AL1(*-TABLEU)
ORG TABLEU+C'a'
DC C'ABCDEFGHI'
ORG TABLEU+C'j'
DC C'JKLMNOPQR'
ORG TABLEU+C's'
DC C'STUVWXYZ'
ORG
TABLEL DC 256AL1(*-TABLEL)
ORG TABLEL+C'A'
DC C'abcdefghi'
ORG TABLEL+C'J'
DC C'jklmnopqr'
ORG TABLEL+C'S'
DC C'stuvwxyz'
ORG
YREGS
END UCASE
- Output:
alphaBETA ALPHABETA alphabeta
4D
$string:="alphaBETA"
$uppercase:=Uppercase($string)
$lowercase:=Lowercase($string)
6502 Assembly
.lf case6502.lst
.cr 6502
.tf case6502.obj,ap1
;------------------------------------------------------
; String Case for the 6502 by barrym95838 2013.04.07
; Thanks to sbprojects.com for a very nice assembler!
; The target for this assembly is an Apple II with
; mixed-case output capabilities. Apple IIs like to
; work in '+128' ascii, so this version leaves bit 7
; alone, and can be used with either flavor.
; 6502s work best with data structures < 256 bytes;
; several instructions would have to be added to
; properly deal with longer strings.
; Tested and verified on AppleWin 1.20.0.0
;------------------------------------------------------
; Constant Section
;
StrPtr = $6 ;0-page temp pointer (2 bytes)
Low = $8 ;0-page temp low bound
High = $9 ;0-page temp high bound
CharOut = $fded ;Specific to the Apple II
BigA = "A" ;'A' for normal ascii
BigZ = "Z" ;'Z' " " "
LittleA = "a" ;'a' " " "
LittleZ = "z" ;'z' " " "
;======================================================
.or $0f00
;------------------------------------------------------
; The main program
;
main ldx #sTest ;Point to the test string
lda /sTest
jsr puts ;print it to stdout
jsr toUpper ;convert to UPPER-case
jsr puts ;print it
jsr toLower ;convert to lower-case
jmp puts ;print it and return to caller
;------------------------------------------------------
toUpper ldy #LittleA
sty Low ;set up the flip range
ldy #LittleZ
bne toLow2 ;return via toLower's tail
;------------------------------------------------------
toLower ldy #BigA
sty Low ;set up the flip range
ldy #BigZ
toLow2 sty High
; ;return via fall-thru to flip
;------------------------------------------------------
; Given a NUL-terminated string at A:X, flip the case
; of any chars in the range [Low..High], inclusive;
; only works on the first 256 bytes of a long string
; Uses: StrPtr, Low, High
; Preserves: A, X
; Trashes: Y
;
flip stx StrPtr ;init string pointer
sta StrPtr+1
ldy #0
pha ;save A
flip2 lda (StrPtr),y ;get string char
beq flip5 ;done if NUL
cmp Low
bcc flip4 ;if Low <= char <= High
cmp High
beq flip3
bcs flip4
flip3 eor #$20 ; then flip the case
sta (StrPtr),y
flip4 iny ;point to next char
bne flip2 ;loop up to 255 times
flip5 pla ;restore A
rts ;return
;------------------------------------------------------
; Output NUL-terminated string @ A:X; strings longer
; than 256 bytes are truncated there
; Uses: StrPtr
; Preserves: A, X
; Trashes: Y
;
puts stx StrPtr ;init string pointer
sta StrPtr+1
ldy #0
pha ;save A
puts2 lda (StrPtr),y ;get string char
beq puts3 ;done if NUL
jsr CharOut ;output the char
iny ;point to next char
bne puts2 ;loop up to 255 times
puts3 pla ;restore A
rts ;return
;------------------------------------------------------
; Test String (in '+128' ascii, Apple II style)
;
sTest .as -"Alpha, BETA, gamma, {[(<123@_>)]}."
.az -#13
;------------------------------------------------------
.en
Output:
Alpha, BETA, gamma, {[(<123@_>)]}. ALPHA, BETA, GAMMA, {[(<123@_>)]}. alpha, beta, gamma, {[(<123@_>)]}.
68000 Assembly
These algorithms work for any ASCII string. The implementation of actually printing the characters is left out, as it is not actually relevant to this task.
UpperCase:
;input: A0 = pointer to the string's base address.
;alters the string in-place.
MOVE.B (A0),D0 ;load a letter
BEQ .Terminated ;we've reached the null terminator.
CMP.B #'a',D0 ;compare to ascii code for a
BCS .overhead ;if less than a, keep looping.
CMP.B #'z',D0 ;compare to ascii code for z
BHI .overhead ;if greater than z, keep looping
AND.B #%1101111,D0 ;this "magic constant" turns lower case to upper case, since they're always 32 apart.
.overhead:
MOVE.B D0,(A0)+ ;store the letter back and increment the pointer.
;If this isn't an alphabetical character, D0 won't change and this store won't affect the string at all.
;If it was a letter, it will have been changed to upper case before storing back.
BRA UpperCase ;next letter
.Terminated:
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LowerCase:
MOVE.B (A0),D0 ;load a letter
BEQ .Terminated ;we've reached the null terminator.
CMP.B #'A',D0 ;compare to ascii code for A
BCS .overhead ;if less than A, keep looping.
CMP.B #'Z',D0 ;compare to ascii code for Z
BHI .overhead ;if greater than Z, keep looping
OR.B #%00100000,D0 ;this "magic constant" turns upper case to lower case, since they're always 32 apart.
.overhead:
MOVE.B D0,(A0)+ ;store the result and get ready to read the next letter.
BRA LowerCase ;next letter
.Terminated:
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
MOVE.B (A0),D0 ;load a letter and inc the pointer to the next letter
BEQ .Terminated ;we've reached the null terminator.
MOVE.B D0,D1 ;copy the letter
AND.B #%11011111 ;convert the copy to upper case so we can check it.
CMP.B #'A',D1 ;compare to ascii code for A
BCS overhead ;if less than A, keep looping.
CMP.B #'Z',D1 ;compare to ascii code for Z
BHI overhead ;if greater than Z, keep looping
EOR.B #%00100000,D0 ;swaps the case of the letter
overhead:
MOVE.B D0,(A0)+ ;store the result
BRA ToggleCase ;next letter
.Terminated:
RTS
8080 Assembly
org 100h
jmp demo
;;; Convert CP/M string under [HL] to upper case
unext: inx h
ucase: mov a,m ; Get character <- entry point is here
cpi '$' ; Done?
rz ; If so, stop
cpi 'a' ; >= 'a'?
jc unext ; If not, next character
cpi 'z'+1 ; <= 'z'?
jnc unext ; If not, next character
sui 32 ; Subtract 32
mov m,a ; Write character back
jmp unext
;;; Convert CP/M string under [HL] to lower case
lnext: inx h
lcase: mov a,m ; Get character <- entry point is here
cpi '$' ; Done?
rz ; If so, stop
cpi 'A' ; >= 'A'?
jc lnext ; If not, next character
cpi 'Z'+1 ; <= 'Z'?
jnc lnext ; If not, next character
adi 32 ; Subtract 32
mov m,a ; Write character back
jmp lnext
;;; Apply to given string
demo: call print ; Print without change
lxi h,str
call ucase ; Make uppercase
call print ; Print uppercase version
lxi h,str
call lcase ; Make lowercase (fall through to print)
print: lxi d,str ; Print string using CP/M call
mvi c,9
jmp 5
str: db 'alphaBETA',13,10,'$'
- Output:
alphaBETA ALPHABETA alphabeta
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strcase64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Result: \n"
szString: .asciz "alphaBETA"
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 64 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sBuffer: .skip 80
sBuffex1: .skip 80
/************************************/
/* code section */
/************************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x1,qAdrszString
ldr x3,qAdrsBuffer
ldr x4,qAdrsBuffex1
mov x6,#0b100000 // 1 -> bit 5
mov x2,#0
1:
ldrb w0,[x1,x2] // load byte of string
mov x5,x0
cmp x0,#'A' // select alpha characters lower or upper
blt 3f
cmp x0,#'z'
bgt 3f
cmp x0,#'Z'
ble 2f
cmp x0,#'a'
bge 2f
b 3f
2:
orr x0,x0,x6 // converion in lower case (1 -> bit 5)
bic x5,x0,x6 // converion in upper case (0 -> bit 5)
3:
strb w0,[x3,x2] // store lower character
strb w5,[x4,x2] // store upper character
cmp x0,#0 // end string ?
add x2,x2,#1 // increment index character
bne 1b // loop
ldr x0,qAdrszMessResult
bl affichageMess
ldr x0,qAdrsBuffer
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x0,qAdrsBuffex1
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszString: .quad szString
qAdrsBuffer: .quad sBuffer
qAdrsBuffex1: .quad sBuffex1
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessStart: .quad szMessStart
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
- Output:
Program 64 bits start. Result: alphabeta ALPHABETA
Action!
INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit
PROC UpperCase(CHAR ARRAY text,res)
BYTE i
res(0)=text(0)
FOR i=1 TO res(0)
DO
res(i)=ToUpper(text(i))
OD
RETURN
PROC LowerCase(CHAR ARRAY text,res)
BYTE i
res(0)=text(0)
FOR i=1 TO res(0)
DO
res(i)=ToLower(text(i))
OD
RETURN
PROC Main()
CHAR ARRAY text="alphaBETA"
CHAR ARRAY upper(20),lower(20)
UpperCase(text,upper)
LowerCase(text,lower)
Put(125) PutE() ;clear screen
PrintF("Original string: ""%S""%E",text)
PrintF("Upper-case string: ""%S""%E",upper)
PrintF("Lower-case string: ""%S""%E",lower)
RETURN
- Output:
Screenshot from Atari 8-bit computer
Original string: "alphaBETA" Upper-case string: "ALPHABETA" Lower-case string: "alphabeta"
ActionScript
var string:String = 'alphaBETA';
var upper:String = string.toUpperCase();
var lower:String = string.toLowerCase();
Ada
with Ada.Characters.Handling, Ada.Text_IO;
use Ada.Characters.Handling, Ada.Text_IO;
procedure Upper_Case_String is
S : constant String := "alphaBETA";
begin
Put_Line (To_Upper (S));
Put_Line (To_Lower (S));
end Upper_Case_String;
ALGOL 68
#!/usr/local/bin/a68g --script #
# Demonstrate toupper and tolower for standard ALGOL 68
strings. This does not work for multibyte character sets. #
INT l2u = ABS "A" - ABS "a";
PROC to upper = (CHAR c)CHAR:
(ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u ));
PROC to lower = (CHAR c)CHAR:
(ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u ));
# Operators can be defined in ALGOL 68 #
OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper;
# upper-cases s in place #
PROC string to upper = (REF STRING s)VOID:
FOR i FROM LWB s TO UPB s DO s[i] := to upper(s[i]) OD;
# lower-cases s in place #
PROC string to lower = (REF STRING s)VOID:
FOR i FROM LWB s TO UPB s DO s[i] := to lower(s[i]) OD;
main: (
STRING t := "alphaBETA";
string to upper(t);
printf(($"uppercase: "gl$, t));
string to lower(t);
printf(($"lowercase: "gl$, t))
)
Output:
uppercase: ALPHABETA lowercase: alphabeta
ALGOL W
begin
% algol W doesn't have standard case conversion routines, this is one way %
% such facilities could be provided %
% converts text to upper case %
% assumes the letters are contiguous in the character set (as in ASCII) %
% would not work in EBCDIC (as the original algol W implementations used) %
procedure upCase( string(256) value result text ) ;
for i := 0 until 255 do begin
string(1) c;
c := text( i // 1 );
if c >= "a" and c <= "z"
then begin
text( i // 1 ) := code( decode( "A" )
+ ( decode( c ) - decode( "a" ) )
)
end
end upCase ;
% converts text to lower case %
% assumes the letters are contiguous in the character set (as in ASCII) %
% would not work in EBCDIC (as the original algol W implementations used) %
procedure dnCase( string(256) value result text ) ;
for i := 0 until 255 do begin
string(1) c;
c := text( i // 1 );
if c >= "A" and c <= "Z"
then begin
text( i // 1 ) := code( decode( "a" )
+ ( decode( c ) - decode( "A" ) )
)
end
end dnCase ;
string(256) text;
text := "alphaBETA";
upCase( text );
write( text( 0 // 40 ) );
dnCase( text );
write( text( 0 // 40 ) );
end.
- Output:
ALPHABETA alphabeta
Amazing Hopper
#include <hopper.h>
#proto swapcase(_X_)
main:
// literal:
String to process = "alphaBETA", {"String to process: ",String to process}println
{"UPPER: ",String to process} upper,println
{"LOWER: ",String to process} lower,println
{"SWAP CASE: "}
s="", let( s := _swap case(String to process)),{s}println
// arrays:
vArray=0, {5,5} new array(vArray), vArray=String to process
{"ARRAY UPPER: \n",vArray} upper,println
{"ARRAY LOWER: \n",vArray} lower,println
[1:2:end,1:2:end]get(vArray),upper, put(vArray)
[2:2:end,2:2:end]get(vArray),lower, put(vArray)
{"INTERVAL ARRAY UPPER/LOWER: \n",vArray},println
exit(0)
.locals
swapcase(_X_)
nLen=0, {_X_}len,mov(nLen)
__SWAPCASE__:
if( [nLen:nLen]get(_X_),{"upper"}!typechar? )
lower
else
upper
end if
put(_X_)
--nLen,{nLen}jnz(__SWAPCASE__)
{_X_} // put processed string into the stack...
back
- Output:
String to process: alphaBETA UPPER: ALPHABETA LOWER: alphabeta SWAP CASE: ALPHAbeta ARRAY UPPER: ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ALPHABETA ARRAY LOWER: alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta alphabeta INTERVAL ARRAY UPPER/LOWER: ALPHABETA alphaBETA ALPHABETA alphaBETA ALPHABETA alphaBETA alphabeta alphaBETA alphabeta alphaBETA ALPHABETA alphaBETA ALPHABETA alphaBETA ALPHABETA alphaBETA alphabeta alphaBETA alphabeta alphaBETA ALPHABETA alphaBETA ALPHABETA alphaBETA ALPHABETA
APL
a←'abcdefghijklmnopqrstuvwxyz' A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ' X←'alphaBETA' (a,⎕AV)[(A,⎕AV)⍳'alphaBETA'] alphabeta (A,⎕AV)[(a,⎕AV)⍳'alphaBETA'] ALPHABETA
In the following example, puntuation is not covered. It is substituted by '*'.
AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ'
AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ*'
AlphUpper[AlphLower⍳'I'm using APL!']
I*M USING APL*
AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ*'
AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ'
AlphLower[AlphUpper⍳'I'm using APL!']
i*m using apl*
APL (Dyalog)
Dyalog APL has a system function for case conversion, ⎕C
. This is Unicode-aware and preserves punctuation. If called monadically, maps character arrays to lower case. If called with a left-hand argument of 1, maps character arrays to upper case.
⎕C 'Πέτρος is using APL!'
πέτροσ is using apl!
1 ⎕C 'Πέτρος is using APL!'
ΠΈΤΡΟΣ IS USING APL!
Note: The I-Beam operator with code 819 is now deprecated in favor of the system function ⎕C
.
AppleScript
AppleScript lacks built in string case functions, but since OS X 10.10 (Yosemite version, Oct 2014) it has been possible to use ObjC Foundation class methods directly in AppleScript code.
use framework "Foundation"
-- TEST -----------------------------------------------------------------------
on run
ap({toLower, toTitle, toUpper}, {"alphaBETA αβγδΕΖΗΘ"})
--> {"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower
-- toTitle :: String -> String
on toTitle(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toTitle
-- toUpper :: String -> String
on toUpper(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toUpper
-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
set {nf, nx} to {length of fs, length of xs}
set lst to {}
repeat with i from 1 to nf
tell mReturn(item i of fs)
repeat with j from 1 to nx
set end of lst to |λ|(contents of (item j of xs))
end repeat
end tell
end repeat
return lst
end ap
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}
Arbre
main():
uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io
Output:
ALPHABETA alphabeta
ARM Assembly
/* ARM assembly Raspberry PI */
/* program strcase.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../constantes.inc"
/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Result: \n"
szString: .asciz "alphaBETA"
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 32 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sBuffer: .skip 80
sBuffer1: .skip 80
/************************************/
/* code section */
/************************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r1,iAdrszString
ldr r3,iAdrsBuffer
ldr r4,iAdrsBuffer1
mov r6,#0b100000 @ 1 -> bit 5
mov r2,#0
1:
ldrb r0,[r1,r2] @ load byte of string
mov r5,r0
cmp r0,#'A' @ select alpha characters lower or upper
blt 3f
cmp r0,#'z'
bgt 3f
cmp r0,#'Z'
ble 2f
cmp r0,#'a'
bge 2f
b 3f
2:
orr r0,r0,r6 @ converion in lower case (1 -> bit 5)
bic r5,r0,r6 @ converion in upper case (0 -> bit 5)
3:
strb r0,[r3,r2] @ store lower character
strb r5,[r4,r2] @ store upper character
cmp r0,#0 @ end string ?
add r2,r2,#1 @ increment index character
bne 1b @ loop
ldr r0,iAdrszMessResult
bl affichageMess
ldr r0,iAdrsBuffer
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrsBuffer1
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszString: .int szString
iAdrsBuffer: .int sBuffer
iAdrsBuffer1: .int sBuffer1
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessStart: .int szMessStart
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
- Output:
Program 32 bits start. Result: alphabeta ALPHABETA
Arturo
str: "alphaBETA"
print ["uppercase :" upper str]
print ["lowercase :" lower str]
print ["capitalize :" capitalize str]
- Output:
uppercase : ALPHABETA lowercase : alphabeta capitalize : AlphaBETA
AutoHotkey
a := "alphaBETA"
StringLower, b, a ; alphabeta
StringUpper, c, a ; ALPHABETA
StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"
AutoIt
$sString = "alphaBETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sLowercase = StringLower($sString) ;"alphabeta"
Avail
Print: uppercase "alphaBETA";
Print: lowercase "alphaBETA";
AWK
BEGIN {
a = "alphaBETA";
print toupper(a), tolower(a)
}
Capitalize:
BEGIN {
a = "alphaBETA";
print toupper(substr(a, 1, 1)) tolower(substr(a, 2))
}
BASIC
s$ = "alphaBETA"
PRINT UCASE$(s$)
PRINT LCASE$(s$)
Applesoft BASIC
S$ = "alphaBETA"
UP$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : UP$ = UP$ + CHR$(C - (C > 96 AND C < 123) * 32) : NEXT I : ? UP$
LO$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : LO$ = LO$ + CHR$(C + (C > 64 AND C < 91) * 32) : NEXT I : ? LO$
BASIC256
s$ = "alphaBETA"
print "Original string: "; s$
print "To Lower case: "; lower(s$)
print "To Upper case: "; upper(s$)
BBC BASIC
INSTALL @lib$+"STRINGLIB"
original$ = "alphaBETA"
PRINT "Original: " original$
PRINT "Lower case: " FN_lower(original$)
PRINT "Upper case: " FN_upper(original$)
PRINT "Title case: " FN_title(original$)
Output:
Original: alphaBETA Lower case: alphabeta Upper case: ALPHABETA Title case: AlphaBETA
Chipmunk Basic
10 s$ = "alphaBETA"
20 print "Original string: ";s$
30 print "To Lower case: ";lcase$(s$)
40 print "To Upper case: ";ucase$(s$)
Commodore BASIC
The example here is based on AppleSoft BASIC, however, Commodore machines have a slightly different interpretation of ASCII:
- On a number of Commodore machines, the default character set at startup is uppercase letters with graphic symbols. In this instance, standard ASCII codes apply, which means printing the result of
ASC("A")
returns65
, and printing the result ofASC("♠")
(SHIFT-A) returns 193. (Not 97... More on this below.) - However, on many of these Commodore machines, the character mode can be changed(†) to an alternate set of glyphs which consists of lowercase letters as well as uppercase letters. When this happens, the former uppercase letter glyphs are replaced with lowercase letter glyphs, and the graphics glyphs are replaced with uppercase letter glyphs. This maintains intuitive use of the computer where typing an uppercase letter is accomplished by holding the SHIFT key while pressing the letter, but the downside is that now the equivalent ASCII codes are reversed: 65 equates to a lowercase "a" (should be 97), and 97 equates to an uppercase "A".
- In addition to all of this, characters 192 through 255 are duplicates of other characters in the lower realms of the table. This allows one to easily use bit 7 as a flag for a shifted character. This is perhaps one reason why BASIC's
ASC
returns values for shifted letters starting at 193. In any case, it needs to be accounted for, and actually makes this task simpler.
† Exceptions to the above would be early PET 2001 models that either had no lowercase letters at all, or had upper and lowercase, but were locked into traditional ASCII encoding. The code example will not behave as expected on these models.
It should be noted that the program starts by sending a control code 14 to the display immediately after clearing the screen, which ensures that the computer is displaying the mixed lowercase/uppercase character set, otherwise the output will be a mix of uppercase letters and graphics.
Code Example
10 rem string case
15 rem rosetta code
20 s$="alphaBETA"
30 print chr$(147);chr$(14)
40 print "The original string is:"
41 print:print tab(11);s$
50 up$="":lo$=""
55 for i=1 to len(s$)
60 c=asc(mid$(s$,i,1))
65 up$=up$+chr$(c or 128)
70 lo$=lo$+chr$(c and 127)
75 next i
80 print:print "Uppercase: ";up$
90 print "Lowercase: ";lo$
- Output:
The original string is: alphaBETA Uppercase: ALPHABETA Lowercase: alphabeta ready. █
FreeBASIC
' FB 1.05.0 Win64
Dim s As String = "alphaBETA"
Print UCase(s)
Print LCase(s)
Sleep
- Output:
ALPHABETA alphabeta
FutureBasic
window 1
CFStringRef s = @"alphaBETA"
print s
print ucase(s)
print lcase(s)
HandleEvents
Output:
alphaBETA ALPHABETA alphabeta
Gambas
Click this link to run this code
Public Sub Main()
Dim sString As String = "alphaBETA "
Print UCase(sString)
Print LCase(sString)
End
Output:
ALPHABETA alphabeta
IS-BASIC
100 INPUT PROMPT "String: ":TX$
110 PRINT "Lower case: ";LCASE$(TX$)
120 PRINT "Upper case: ";UCASE$(TX$)
Liberty BASIC
input$ ="alphaBETA"
print input$
print upper$( input$)
print lower$( input$)
end
PureBasic
s$ = "alphaBETA"
upper$ = UCase(s$) ;uppercase
lower$ = LCase(s$) ;lowercase
QBasic
s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case: "; LCASE$(s$)
PRINT "To Upper case: "; UCASE$(s$)
Run BASIC
a$ ="alphaBETA"
print a$ '=> alphaBETA
print upper$(a$) '=> ALPHABETA
print lower$(a$) '=> alphabeta
TI-83 BASIC
Note: While lowercase letters are built in to every TI-83/4/+/SE calculator, typing in lowercase is disabled by default and you have to hack the calculator to type in lowercase. However, the calculator does not have to be hacked to simply display lowercase output from a program, so on non-hacked calculators this program will only be useful one-way. To get lowercase letters, you have to create a new program with "AsmPrgmFDCB24DEC9" as the text, and then execute it on the homescreen with Asm(prgmYOURPROGRAMNAME). Then press [ALPHA] twice.
True BASIC
LET s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case: "; LCASE$(s$)
PRINT "To Upper case: "; UCASE$(s$)
END
Visual Basic
Sub Main()
Const TESTSTRING As String = "alphaBETA"
Debug.Print "initial = " _
& TESTSTRING
Debug.Print "uppercase = " _
& UCase(TESTSTRING)
Debug.Print "lowercase = " _
& LCase(TESTSTRING)
Debug.Print "first letter capitalized = " _
& StrConv(TESTSTRING, vbProperCase)
Debug.Print "length (in characters) = " _
& CStr(Len(TESTSTRING))
Debug.Print "length (in bytes) = " _
& CStr(LenB(TESTSTRING))
Debug.Print "reversed = " _
& StrReverse(TESTSTRING)
Debug.Print "first position of letter A (case-sensitive) = " _
& InStr(1, TESTSTRING, "A", vbBinaryCompare)
Debug.Print "first position of letter A (case-insensitive) = " _
& InStr(1, TESTSTRING, "A", vbTextCompare)
Debug.Print "concatenated with '123' = " _
& TESTSTRING & "123"
End Sub
- Output:
initial = alphaBETA uppercase = ALPHABETA lowercase = alphabeta first letter capitalized = Alphabeta length (in characters) = 9 length (in bytes) = 18 reversed = ATEBahpla first position of letter A (case-sensitive) = 9 first position of letter A (case-insensitive) = 1 concatenated with '123' = alphaBETA123
Visual Basic .NET
' Define 's'
Dim s AS String = "alphaBETA"
' Change 's' to Upper Case.
s = s.ToUpper()
' Change 's' to Lower Case.
s = s.ToLower()
:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9
:"abcdefghijklmnopqrstuvwxyz"→Str0
:Input ">",Str1
:":"+Str1+":"→Str1
:Prompt U
:If U:Then
:For(I,2,length(Str1))
:If inString(Str0,sub(Str1,I,1)) and sub(Str1,I,1)≠":"
:sub(Str1,1,I-1)+sub(Str9,inString(Str0,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1
:End
:Else
:For(I,2,length(Str1))
:If inString(Str9,sub(Str1,I,1)) and sub(Str1,I,1)≠":"
:sub(Str1,1,I-1)+sub(Str0,inString(Str9,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1
:End
:End
:sub(Str1,2,length(Str1)-2)→Str1
:Pause Str1
XBasic
PROGRAM "StringCase"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
s$ = "alphaBETA"
PRINT "Original string: "; s$
PRINT "To Lower case: "; LCASE$(s$)
PRINT "To Upper case: "; UCASE$(s$)
END FUNCTION
END PROGRAM
Yabasic
s$ = "alphaBETA"
print "Original string: ", s$
print "To Lower case: ", lower$(s$)
print "To Upper case: ", upper$(s$)
BCPL
get "libhdr"
// Check whether a character is an upper or lowercase letter
let islower(x) = 'a' <= x <= 'z'
let isupper(x) = 'A' <= x <= 'Z'
// Convert a character to upper or lowercase
let toupper(x) = islower(x) -> x - 32, x
let tolower(x) = isupper(x) -> x + 32, x
// Map a character function over a string
let strmap(f,s) = valof
$( for i=1 to s%0 do s%i := f(s%i)
resultis s
$)
// Convert a string to upper or lowercase
let strtoupper(s) = strmap(toupper,s)
let strtolower(s) = strmap(tolower,s)
let start() be
$( let s = "alphaBETA"
writef(" String: %S*N", s)
writef("Uppercase: %S*N", strtoupper(s))
writef("Lowercase: %S*N", strtolower(s))
$)
- Output:
String: alphaBETA Uppercase: ALPHABETA Lowercase: alphabeta
Beef
using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
- Output:
ALPHABETA alphabeta
Befunge
Converts to uppercase only; lowercase is done in a similar way so I chose not to add it.
"ATEBahpla" > : #v_ 25* , @ >48*-v
> :: "`"` \"{"\` * | > , v
> ^
^ <
BQN
Both idioms are from BQNcrate. For reference, ⍋
in both examples performs a binary search to check if the characters are in the respective alphabet range. Based on that, the correct number is added at those locations to change case.
Upr ← -⟜(32×1="a{"⊸⍋) # Uppercase ASCII text
Lwr ← +⟜(32×1="A["⊸⍋) # Lowercase ASCII text
str ← "alphaBETA"
"alphaBETA"
Upr str
"ALPHABETA"
Lwr str
"alphabeta"
Bracmat
The functions upp$
and low$
assume that strings are UTF-8 encoded, but if a string is not valid UTF-8, it is assumed the string is ISO-8859-1. Case conversion is not restricted to the Latin alphabet, but extends to all alphabets that have upper and lower case characters.
"alphaBETA":?s
& out$str$(upp$!s \n low$!s)
Output:
ALPHABETA alphabeta
Burlesque
blsq ) "alphaBETA"^^zz\/ZZ
"ALPHABETA"
"alphabeta"
C
The tolower and toupper functions are locale-aware.
/* Demonstrate toupper and tolower for
standard C strings.
This does not work for multibyte character sets. */
#include <ctype.h>
#include <stdio.h>
/* upper-cases s in place */
void str_toupper(char *s)
{
while(*s)
{
*s=toupper(*s);
s++;
}
}
/* lower-cases s in place */
void str_tolower(char *s)
{
while(*s)
{
*s=tolower(*s);
s++;
}
}
int main(int argc, char *argv[])
{
char t[255]="alphaBETA";
str_toupper(t);
printf("uppercase: %s\n", t);
str_tolower(t);
printf("lowercase: %s\n", t);
return 0;
}
C#
class Program
{
static void Main(string[] args)
{
string input;
Console.Write("Enter a series of letters: ");
input = Console.ReadLine();
stringCase(input);
}
private static void stringCase(string str)
{
char[] chars = str.ToCharArray();
string newStr = "";
foreach (char i in chars)
if (char.IsLower(i))
newStr += char.ToUpper(i);
else
newStr += char.ToLower(i);
Console.WriteLine("Converted: {0}", newStr);
}
}
Title case is a little different:
System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
C++
This method does the transform in-place. Alternate methods might return a new copy or use a stream manipulator.
#include <algorithm>
#include <string>
#include <cctype>
/// \brief in-place convert string to upper case
/// \return ref to transformed string
void str_toupper(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::toupper);
}
/// \brief in-place convert string to lower case
/// \return ref to transformed string
void str_tolower(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::tolower);
}
Here is sample usage code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string foo("_upperCas3Me!!");
str_toupper(foo);
cout << foo << endl;
str_tolower(foo);
cout << foo << endl;
return 0;
}
Clojure
(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string))
CMake
string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}")
-- Uppercase: ALPHABETA -- Lowercase: alphabeta
COBOL
Standard-compliant Methods
IDENTIFICATION DIVISION.
PROGRAM-ID. string-case-85.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 example PIC X(9) VALUE "alphaBETA".
01 result PIC X(9).
PROCEDURE DIVISION.
DISPLAY "Example: " example
*> Using the intrinsic functions.
DISPLAY "Lower-case: " FUNCTION LOWER-CASE(example)
DISPLAY "Upper-case: " FUNCTION UPPER-CASE(example)
*> Using INSPECT
MOVE example TO result
INSPECT result CONVERTING "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
TO "abcdefghijklmnopqrstuvwxyz"
DISPLAY "Lower-case: " result
MOVE example TO result
INSPECT result CONVERTING "abcdefghijklmnopqrstuvwxyz"
TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DISPLAY "Upper-case: " result
GOBACK
.
Compiler Extensions
IDENTIFICATION DIVISION.
PROGRAM-ID. string-case-extensions.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 example VALUE "alphaBETA".
01 result PIC X(9).
PROCEDURE DIVISION.
DISPLAY "Example: " example
*> ACUCOBOL-GT
MOVE example TO result
CALL "C$TOLOWER" USING result, BY VALUE 9
DISPLAY "Lower-case: " result
MOVE example TO result
CALL "C$TOUPPER" USING result, BY VALUE 9
DISPLAY "Upper-case: " result
*> Visual COBOL
MOVE example TO result
CALL "CBL_TOLOWER" USING result, BY VALUE 9
DISPLAY "Lower-case: " result
MOVE example TO result
CALL "CBL_TOUPPER" USING result BY VALUE 9
DISPLAY "Upper-case: " result
GOBACK
.
ColdFusion
converting a string literal
<cfset upper = UCase("alphaBETA")>
<cfset lower = LCase("alphaBETA")>
converting the value of a variable
<cfset string = "alphaBETA">
<cfset upper = UCase(string)>
<cfset lower = LCase(string)>
Common Lisp
You can use the string-upcase function to perform upper casing:
CL-USER> (string-upcase "alphaBETA")
"ALPHABETA"
and you can do lower casing by using string-downcase:
CL-USER> (string-downcase "alphaBETA")
"alphabeta"
Component Pascal
BlackBox Component Builder
MODULE AlphaBeta;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
str,res: ARRAY 128 OF CHAR;
BEGIN
str := "alphaBETA";
Strings.ToUpper(str,res);
StdLog.String("Uppercase:> ");StdLog.String(res);StdLog.Ln;
Strings.ToLower(str,res);
StdLog.String("Lowercase:> ");StdLog.String(res);StdLog.Ln
END Do;
END AlphaBeta.
Execute: ^Q AlphaBeta.Do
Output:
Uppercase:> ALPHABETA Lowercase:> alphabeta
Crystal
"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".capitalize # => "Alphabeta"
Fully works with all Unicode range.
"ĥåçýджк".upcase # => "ĤÅÇÝДЖК"
D
void main() {
import std.stdio, std.string;
immutable s = "alphaBETA";
s.toUpper.writeln;
s.toLower.writeln;
}
- Output:
ALPHABETA alphabeta
Dart
String capitalize(String string) {
if (string.isEmpty) {
return string;
}
return string[0].toUpperCase() + string.substring(1);
}
void main() {
var s = 'alphaBETA';
print('Original string: $s');
print('To Lower case: ${s.toLowerCase()}');
print('To Upper case: ${s.toUpperCase()}');
print('To Capitalize: ${capitalize(s)}');
}
- Output:
Original string: alphaBETA To Lower case: alphabeta To Upper case: ALPHABETA To Capitalize: AlphaBETA
DBL
OPEN (1,O,'TT:') ;open video
STR="alphaBETA"
LOCASE STR
DISPLAY (1,STR,10) ;alphabeta
UPCASE STR
DISPLAY (1,STR,10) ;ALPHABETA
Delphi
writeln(uppercase('alphaBETA'));
writeln(lowercase('alphaBETA'));
DWScript
PrintLn(UpperCase('alphaBETA'));
PrintLn(LowerCase('alphaBETA'));
Dyalect
let str = "alphaBETA"
print("Lower case: ", str.Lower(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Capitalize: ", str.Capitalize(), separator: "")
E
["alphaBETA".toUpperCase(),
"alphaBETA".toLowerCase()]
EasyLang
EasyLang does not have string case functions. The functions provided below only work with ASCII.
func$ toUpper s$ .
for c$ in strchars s$
code = strcode c$
if code >= 97 and code <= 122
code -= 32
.
res$ &= strchar code
.
return res$
.
func$ toLower s$ .
for c$ in strchars s$
code = strcode c$
if code >= 65 and code <= 90
code += 32
.
res$ &= strchar code
.
return res$
.
string$ = "alphaBETA"
print string$
print toUpper string$
print toLower string$
- Output:
alphaBETA ALPHABETA alphabeta
EchoLisp
EchoLisp includes the usual case conversion functions and the randcase function : random case
(string-downcase "alphaBETA")
→ "alphabeta"
(string-upcase "alphaBETA")
→ "ALPHABETA"
(string-titlecase "alphaBETA")
→ "Alphabeta"
(string-randcase "alphaBETA")
→ "alphaBEtA"
(string-randcase "alphaBETA")
→ "AlPHaBeTA"
ECL
IMPORT STD; //Imports the Standard Library
STRING MyBaseString := 'alphaBETA';
UpperCased := STD.str.toUpperCase(MyBaseString);
LowerCased := STD.str.ToLowerCase(MyBaseString);
TitleCased := STD.str.ToTitleCase(MyBaseString);
OUTPUT (UpperCased);
OUTPUT (LowerCased);
OUTPUT (TitleCased);
Ecstasy
The methods on String
are toUppercase()
and toLowercase()
:
module test {
void run() {
@Inject Console console;
console.print($"{"alphaBETA".toLowercase()=}");
console.print($"{"alphaBETA".toUppercase()=}");
}
}
- Output:
x$ xec test "alphaBETA".toLowercase()=alphabeta "alphaBETA".toUppercase()=ALPHABETA
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:
alphaBETA alphaBETA alphaBETA
With the following script, saved as String_case.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
... and the command line:
ed -s in < String_case.ed
- Output:
ALPHABETA alphabeta AlphaBETA
... 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.
Elena
ELENA 6.x:
import system'culture;
public program()
{
string s1 := "alphaBETA";
console.writeLine(s1.toLower(currentLocale));
console.writeLine(s1.toUpper(currentLocale));
console.readChar()
}
Elixir
The String module provides the following functions:
String.downcase("alphaBETA")
# => alphabeta
String.upcase("alphaBETA")
# => ALPHABETA
String.capitalize("alphaBETA")
# => Alphabeta
As with most String functions in Elixir, these are fully compatible with Unicode.
String.downcase("αΒ")
# => αβ
String.upcase("αΒ")
# => ΑΒ
String.capitalize("αΒ")
# => Αβ
String.upcase("ß")
# => SS
Elm
import String exposing (toLower, toUpper)
s = "alphaBETA"
lower = toLower s
upper = toUpper s
EMal
var samples = text["alphaBETA", "ação", "o'hare O'HARE o’hare don't", "Stroßbùrri", "ĥåçýджк", "DŽLjnj"]
for each var sample in samples
writeLine(" original : " + sample)
writeLine(" lower : " + sample.lower())
writeLine(" upper : " + sample.upper())
writeLine()
end
- Output:
original : alphaBETA lower : alphabeta upper : ALPHABETA original : ação lower : ação upper : AÇÃO original : o'hare O'HARE o’hare don't lower : o'hare o'hare o’hare don't upper : O'HARE O'HARE O’HARE DON'T original : Stroßbùrri lower : stroßbùrri upper : STROßBÙRRI original : ĥåçýджк lower : ĥåçýджк upper : ĤÅÇÝДЖК original : DŽLjnj lower : džljnj upper : DŽLJNJ
Erlang
string:to_upper("alphaBETA").
string:to_lower("alphaBETA").
Excel
Take 3 cells, say A1,B1 and C1. In B1 type :
=LOWER(A1)
and in C1 :
=UPPER(A1)
For the stated input in A1, the result will be :
alphaBETA alphabeta ALPHABETA
F#
let s = "alphaBETA"
let upper = s.ToUpper()
let lower = s.ToLower()
Factor
"alphaBETA" >lower ! "alphabeta"
"alphaBETA" >upper ! "ALPHABETA"
"alphaBETA" >title ! "Alphabeta"
"ß" >case-fold ! "ss"
Falcon
printl("alphaBETA".lower())
printl("alphaBETA".upper())
Fantom
fansh> a := "alphaBETA"
alphaBETA
fansh> a.upper // convert whole string to upper case
ALPHABETA
fansh> a.lower // convert whole string to lower case
alphabeta
fansh> a.capitalize // make sure first letter is capital
AlphaBETA
fansh> "BETAalpha".decapitalize // make sure first letter is not capital
bETAalpha
Forth
ANS Forth does not have words to convert case for either strings or characters. For known alpha-numeric ASCII characters, the following can be used:
: tolower ( C -- c ) 32 or ; : toupper ( c -- C ) 32 invert and ; : lower ( addr len -- ) over + swap do i c@ tolower i c! loop ; : upper ( addr len -- ) over + swap do i c@ toupper i c! loop ;
If the character range is unknown, these definitions are better:
: tolower ( C -- c ) dup [char] A [char] Z 1+ within if 32 + then ; : toupper ( c -- C ) dup [char] a [char] z 1+ within if 32 - then ;
create s ," alphaBETA" s count type s count 2dup upper type s count 2dup lower type
Output:
alphaBETA ALPHABETA alphabeta
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
Functions could be used instead, especially with later compilers that enable lengths not fixed at compile time, but this involves copying the text about. By contrast, the subroutines alter the text in-place, though if something like Utext = Uppercase(text)
is desired so that both versions are available, a subroutine is less convenient.
F90 introduced the intrinsic function i = IACHAR(c), which returns the integer value of the position of character c in the ASCII character set, even if the processor's default character set is different, such as perhaps EBCDIC. Function ACHAR is the inverse. If the bit pattern of the character was not being interpreted as in the ASCII set, this will cause odd results, say on a system using EBCDIC or (on an ASCII-using cpu) for a file originating from an EBCDIC-using system. Some systems offer additional options to the file OPEN statement that enable character conversion between ASCII and EBCDIC, and there may also be options concerning big- and little-endian usage. But much will depend on the format of the data in the file. If the data are a mixture of text, integers, floating-point, etc. all in binary, there will be no hope for such simple translations.
For converting lower-case text to upper, the following will work both on an ASCII system and an EBCDIC system (or any other encodement), once it is compiled for that system:
SUBROUTINE UPCASE(TEXT)
CHARACTER*(*) TEXT
INTEGER I,C
DO I = 1,LEN(TEXT)
C = INDEX("abcdefghijklmnopqrstuvwxyz",TEXT(I:I))
IF (C.GT.0) TEXT(I:I) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"(C:C)
END DO
END
The INDEX function of course returning zero if the character is not found. Converting from upper to lower case is the obvious inverse and it might be worthwhile defining a MODULE with suitable named character constants to avoid repetition - one might hope the compiler will share duplicated constants rather than producing a fresh version every time, but it might not too. The repeated text scanning done by the INDEX function for each character of TEXT will of course be a lot slower. A still-more advanced compiler might be able to take advantage of special translation op-codes, on systems that offer them. If storage space is not at a premium a swifter method would be to create something like CHARACTER*1 XLATUC(0:255)
with most entries being equal to their index, except for those corresponding to the lower case letters for which the value is the corresponding upper case letter. Then
DO I = 1,LEN(TEXT)
TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))
END DO
Note that in EBCDIC the offset is not 32 but 64. Rather than using an undocumented "magic constant" such as 32, one could define PARAMETER (HIC = ICHAR("A") - ICHAR("a"))
instead or just place such code in-line and have hope for the compiler. This would also handle the small detail that "A" > "a" in EBCDIC rather than ASCII's "A" < "a". But alas, in EBCDIC the letter codes are not contiguous (there are many non-letter symbols between "a" and "z" as well as between "A" and "Z"), so the bounds of "A" to "Z" will not isolate only letters for attack. And it was not just IBM mainframes that used various versions of EBCDIC, so also did Burroughs, among others.
Here a complete example, using functions, and as far as I can tell, will work also with EBCDIC:
module uplow
implicit none
character(len=26), parameter, private :: low = "abcdefghijklmnopqrstuvwxyz"
character(len=26), parameter, private :: high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
contains
function to_upper(s) result(t)
! returns upper case of s
implicit none
character(len=*), intent(in) :: s
character(len=len(s)) :: t
character(len=1), save :: convtable(0:255)
logical, save :: first = .true.
integer :: i
if(first) then
do i=0,255
convtable(i) = char(i)
enddo
do i=1,len(low)
convtable(iachar(low(i:i))) = char(iachar(high(i:i)))
enddo
first = .false.
endif
t = s
do i=1,len_trim(s)
t(i:i) = convtable(iachar(s(i:i)))
enddo
end function to_upper
function to_lower(s) result(t)
! returns lower case of s
implicit none
character(len=*), intent(in) :: s
character(len=len(s)) :: t
character(len=1), save :: convtable(0:255)
logical, save :: first = .true.
integer :: i
if(first) then
do i=0,255
convtable(i) = char(i)
enddo
do i = 1,len(low)
convtable(iachar(high(i:i))) = char(iachar(low(i:i)))
enddo
first = .false.
endif
t = s
do i=1,len_trim(s)
t(i:i) = convtable(iachar(s(i:i)))
enddo
end function to_lower
end module uplow
program doit
use uplow
character(len=40) :: s
s = "abcdxyz ZXYDCBA _!@"
print *,"original: ",'[',s,']'
print *,"to_upper: ",'[',to_upper(s),']'
print *,"to_lower: ",'[',to_lower(s),']'
end program doit
Frink
a = "alphaBETA"
println[lc[a]]
println[uc[a]]
These functions use Unicode single- and multiple-character mapping tables and thus try to do the right thing with Unicode, possibly making the string longer in some cases:
uc["Imbiß"] // Last char is \u00df
Produces:
IMBISS
As the Unicode standard for casing states, "it is important to note that no casing operations on strings are reversible:"
lc[ uc["Imbiß"] ]
imbiss
GAP
LowercaseString("alphaBETA");
UppercaseString("alphaBETA");
GDScript
extends MainLoop
func _process(_delta: float) -> bool:
var string: String = "alphaBETA"
print(string.to_upper())
print(string.to_lower())
# Note: These will also add/remove underscores.
print("to_camel_case: ", string.to_camel_case())
print("to_pascal_case: ", string.to_pascal_case())
print("to_snake_case: ", string.to_snake_case())
return true # Exit
- Output:
ALPHABETA alphabeta to_camel_case: alphaBeta to_pascal_case: AlphaBeta to_snake_case: alpha_beta
GML
#define cases
{
x = 'alphaBETA';
y = string_upper(x); // returns ALPHABETA
z = string_lower(x); // returns alphabeta
show_message(y);
show_message(z);
}
Go
"Title case" in Go's Unicode package does not mean capitalize the first letter of each word, but rather capitalize each letter as if it were the first letter of a word. The distinction matters in languages such as Croatian with digraphs with a capitialized form that is different from the all-caps form. ToTitle() converts a string to all title case.
It is Title() on the other hand, that capitalizes the first letter of each word. It identifies word boundaries and capitalizes first letters, leaving other letters unmodified. As of Go 1.2 though, the word breaking algorithm is not Unicode compliant.
package main
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
func main() {
show("alphaBETA")
show("alpha BETA")
// Three digraphs that should render similar to DZ, Lj, and nj.
show("DŽLjnj")
// Unicode apostrophe in third word.
show("o'hare O'HARE o’hare don't")
}
func show(s string) {
fmt.Println("\nstring: ",
s, " len:", utf8.RuneCountInString(s), "runes") // DZLjnj
fmt.Println("All upper case: ", strings.ToUpper(s)) // DZLJNJ
fmt.Println("All lower case: ", strings.ToLower(s)) // dzljnj
fmt.Println("All title case: ", strings.ToTitle(s)) // DzLjNj
fmt.Println("Title words: ", strings.Title(s)) // Dzljnj
fmt.Println("Swapping case: ", // DzLjNJ
strings.Map(unicode.SimpleFold, s))
}
- Output:
string: alphaBETA len: 9 runes All upper case: ALPHABETA All lower case: alphabeta All title case: ALPHABETA Title words: AlphaBETA Swapping case: ALPHAbeta string: alpha BETA len: 10 runes All upper case: ALPHA BETA All lower case: alpha beta All title case: ALPHA BETA Title words: Alpha BETA Swapping case: ALPHA beta string: DŽLjnj len: 3 runes All upper case: DŽLJNJ All lower case: džljnj All title case: DžLjNj Title words: DžLjnj Swapping case: DžljNJ string: o'hare O'HARE o’hare don't len: 26 runes All upper case: O'HARE O'HARE O’HARE DON'T All lower case: o'hare o'hare o’hare don't All title case: O'HARE O'HARE O’HARE DON'T Title words: O'Hare O'HARE O’hare Don'T Swapping case: O'HARE o'hare O’HARE DON'T
Go handles many Unicode characters upcasing well but fails for some like ß where it hasn't changed ß
into SS
(expected STROSSBÙRRI
).
package main
import (
"fmt"
"strings"
)
func main() {
a := "Stroßbùrri"
b := "ĥåçýджк"
fmt.Println(strings.ToUpper(a))
fmt.Println(strings.ToUpper(b))
}
}
- Output:
STROßBÙRRI ĤÅÇÝДЖК
Groovy
def str = 'alphaBETA'
println str.toUpperCase()
println str.toLowerCase()
Output:
ALPHABETA alphabeta
Haskell
import Data.Char
s = "alphaBETA"
lower = map toLower s
upper = map toUpper s
HicEst
CHARACTER str = "alphaBETA"
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, UpperCase=1)
Icon and Unicon
IDL
str = "alphaBETA" print, str print, strupcase(str) print, strlowcase(str)
J
Use standard utilities:
toupper 'alphaBETA'
ALPHABETA
tolower 'alphaBETA'
alphabeta
or alternative definitions:
upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.)
lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.)
For example:
upper 'alphaBETA'
ALPHABETA
lower 'alphaBETA'
alphabeta
Java
The String class offers the toUpperCase and toLowerCase methods. There is no title-case, alternate-case, or sentence-case methods.
String string = "alphaBETA".toUpperCase();
String string = "alphaBETA".toLowerCase();
Alternately
String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
//Also works with non-English characters with no modification
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß"
You could also easily create a swapCase method using Character.isLowerCase(), Character.isUpperCase(), and Character.isLetter().
JavaScript
alert( "alphaBETA".toUpperCase() );
alert( "alphaBETA".toLowerCase() );
Output:
ALPHABETA alphabeta
var string = "alphaBETA";
var uppercase = string.toUpperCase();
var lowercase = string.toLowerCase();
Joy
DEFINE
islower == ord 109.5 - abs 13 <;
isupper == ord 77.5 - abs 13 <;
tolower == [[isupper] [32 +] [] ifte] map;
toupper == [[islower] [32 -] [] ifte] map.
"alphaBETA" tolower.
"alphaBETA" toupper.
jq
Works with jq and gojq, the C and Go implementations of jq
If your version of jq does not have ascii_downcase and ascii_upcase, then you might want to use their definitions:
# like ruby's downcase - only characters A to Z are affected
def ascii_downcase:
explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;
# like ruby's upcase - only characters a to z are affected
def ascii_upcase:
explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;
jq's regular expression functions have a "case insensitive" option that is often useful when handling text outside the ASCII range, as is illustrated by the last example below. Currently, however, there is no built-in case-conversion filter for Unicode characters in general.
Examples:
"alphaBETA" | ascii_upcase
#=> "ALPHABETA"
"alphaBETA" | ascii_downcase
#=> "alphabeta"
jq -n '"á" | test("Á";"i")' # case-insensitive search
#=> true
Jsish
var msg = "alphaBETA";
;msg;
;msg.toUpperCase();
;msg.toLowerCase();
;msg.toTitle();
;msg.toLocaleUpperCase();
;msg.toLocaleLowerCase();
- Output:
prompt$ jsish --U string-case.jsi msg ==> alphaBETA msg.toUpperCase() ==> ALPHABETA msg.toLowerCase() ==> alphabeta msg.toTitle() ==> Alphabeta msg.toLocaleUpperCase() ==> ALPHABETA msg.toLocaleLowerCase() ==> alphabeta
Julia
julia> uppercase("alphaBETA")
"ALPHABETA"
julia> lowercase("alphaBETA")
"alphabeta"
Some letters like ß (U+00DF) are transformed to ẞ (U+1E9E) in Julia, instead of SS (2 𝗑 U+0053) as expected of the Unicode standard[1].
julia> a = 'ß'
'ß': Unicode U+00DF (category Ll: Letter, lowercase)
julia> uppercase(a)
'ẞ': Unicode U+1E9E (category Lu: Letter, uppercase)
K
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"
s:"alphaBETA"
upper: {`c$x+-32*(x>"`")*x<"{"}
lower: {`c$x+32*(x>"@")*x<"["}
lower:_: / built in
upper "This is a test."
"THIS IS A TEST."
lower "This is a test."
"this is a test."
lower s
"alphabeta"
upper s
"ALPHABETA"
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
val s = "alphaBETA"
println(s.toUpperCase())
println(s.toLowerCase())
println(s.capitalize())
println(s.decapitalize())
}
- Output:
ALPHABETA alphabeta AlphaBETA alphaBETA
Lambdatalk
Lambdatalk can take benefit from CSS rules.
{span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta
{span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA
Lang
$s = alphaBETA
fn.println(fn.toUpper($s))
fn.println(fn.toLower($s))
- Output:
ALPHABETA alphabeta
Lasso
// Direct string return
'alphaBETA'->uppercase&
'alphaBETA'->lowercase&
// Assignment and manipulation of variables
local(toupper = 'alphaBETA')
#toupper->uppercase
#toupper
local(tolower = 'alphaBETA')
#tolower->lowercase
#tolower
Lingo
Lingo has no case conversion functions, but for ASCII strings they can e.g. be implemented like this:
----------------------------------------
-- Lower to upper case (ASCII only)
-- @param {string} str
-- @return {string}
----------------------------------------
on toUpper (str)
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
len = str.length
repeat with i = 1 to len
pos = offset(str.char[i], alphabet)
if pos > 0 then put alphabet.char[pos] into char i of str
end repeat
return str
end
----------------------------------------
-- Upper to lower case (ASCII only)
-- @param {string} str
-- @return {string}
----------------------------------------
on toLower (str)
alphabet = "abcdefghijklmnopqrstuvwxyz"
len = str.length
repeat with i = 1 to len
pos = offset(str.char[i], alphabet)
if pos > 0 then put alphabet.char[pos] into char i of str
end repeat
return str
end
put toUpper("alphaBETA")
-- "ALPHABETA"
put toLower("alphaBETA")
-- "alphabeta"
LiveCode
put upper("alphaBETA") && lower("alphaBETA")
ALPHABETA alphabeta
Logo
print uppercase "alphaBETA ; ALPHABETA print lowercase "alphaBETA ; alphabeta
Lua
str = "alphaBETA"
print( string.upper(str) ) -- ALPHABETA
print( string.lower(str) ) -- alphabeta
print ( str:upper() ) -- ALPHABETA
print ( str:lower() ) -- alphabeta
The string library properly works only for ASCII and extended ASCII (depending on the locals) ranges but not for Unicode.
print ( string.upper("ação") ) -- returns AçãO instead of AÇÃO
print ( string.upper("ĥåçýджк") ) -- returns ĥåçýджк instead of ĤÅÇÝДЖК
M2000 Interpreter
Module stringcase {
string s="alphaBETA", s1=s, c="!@@@@<"
print ucase$(s)="ALPHABETA"
print lcase$(s)="alphabeta"
s=str$(s+"ΑΛΦΑ", 1032) ' convert from utf16le to ansi 1032, and enpand to utf16LE as locale 1033
print s="alphaBETAÁËÖÁ"
// trait as utfLE16 but for character code from 0 to 255, and return based on locale 1033
print lcase$(s, 1033)="alphabetaáëöá"
// trait as utfLE16 but for character code from 0 to 255, and return based on locale 1032
print lcase$(s, 1032)="alphabetaαλφα"
print lcase$(s1+"ΑΛΦΑ")="alphabetaαλφα"
print str$(s1, ">")="ALPHABETA"
print str$(s1, "<")="alphabeta"
print str$(s1, c)="beta"
}
stringcase
- Output:
True True True True True True True True True
M4
define(`upcase', `translit(`$*', `a-z', `A-Z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')
define(`x',`alphaBETA')
upcase(x)
downcase(x)
Maple
str := "alphaBETA";
StringTools:-UpperCase(str);
StringTools:-LowerCase(str);
produces
alphabeta
ALPHABETA
Mathematica /Wolfram Language
str="alphaBETA";
ToUpperCase[str]
ToLowerCase[str]
- Output:
ALPHABETA alphabeta
MATLAB / Octave
>> upper('alphaBETA')
ans =
ALPHABETA
>> lower('alphaBETA')
ans =
alphabeta
Maxima
supcase('alphaBETA');
sdowncase('alphaBETA');
MAXScript
Requires MAX 2008
str = "alphaBETA"
print (toUpper str)
print (toLower str)
Mercury
The functions to_upper/1, to_lower/1, capitalize_first/1 and uncapitalize_first/1 only affect unaccented Latin characters.
:- module string_case.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
main(!IO) :-
S = "alphaBETA",
io.format("uppercase : %s\n", [s(to_upper(S))], !IO),
io.format("lowercase : %s\n", [s(to_lower(S))], !IO),
io.format("capitalize first: %s\n", [s(capitalize_first(S))], !IO).
% We can use uncaptitalize_first/1 to ensure the first character in a
% string is lower-case.
Metafont
We need to implement it, since it is not already given; the following code works only for ASCII or ASCII based encodings. (It could work anyway also for single byte encodings where letters are contiguous).
vardef isbetween(expr a, i, f) =
if string a:
if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)):
true
else:
false
fi
else:
false
fi enddef;
vardef toupper(expr s) =
save ?; string ?; ? := ""; d := ASCII"A" - ASCII"a";
for i = 0 upto length(s)-1:
if isbetween(substring(i, i+1) of s, "a", "z"):
? := ? & char(ASCII(substring(i,i+1) of s) + d)
else:
? := ? & substring(i, i+1) of s
fi;
endfor
?
enddef;
vardef tolower(expr s) =
save ?; string ?; ? := ""; d := ASCII"a" - ASCII"A";
for i = 0 upto length(s)-1:
if isbetween(substring(i, i+1) of s, "A", "Z"):
? := ? & char(ASCII(substring(i,i+1) of s) + d)
else:
? := ? & substring(i, i+1) of s
fi;
endfor
?
enddef;
message toupper("alphaBETA");
message tolower("alphaBETA");
end
min
"alphaBETA" uppercase
"alphaBETA" lowercase
"alphaBETA" capitalize
MiniScript
mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower
- Output:
Upper Case of alphaBETA is ALPHABETA Lower Case of alphaBETA is alphabeta
MIPS Assembly
These examples modify a string in place. $a0
is assumed to contain a pointer to the string in RAM; writes to ROM will obviously not have the desired effect.
ToUpper:
;input: $a0 = pointer to beginning of string
;clobbers: $t0,$t1,$t2
li $t1,'a'
li $t2,'z'
ToUpper_again:
lbu $t0,($a0)
nop
beqz $t0,ToUpper_done ;if char is null terminator, exit
nop
bltu $t0,$t1,ToUpper_overhead ;if char stored in $t0 < 'a', skip
nop
bgtu $t0,$t2,ToUpper_overhead ;if char stored in $t0 > 'z', skip
nop
andi $t0,$t0,0xDF ;otherwise, do the work.
sb $t0,($a0)
ToUpper_overhead:
addiu $a0,1
b ToUpper_again
nop
ToUpper_done:
jr ra
nop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToLower:
;input: $a0 = pointer to beginning of string
;clobbers: $t0,$t1,$t2
li $t1,'A'
li $t2,'Z'
ToLower_again:
lbu $t0,($a0)
nop
beqz $t0,ToUpper_done ;not a typo, I did this to save space.
nop
bltu $t0,$t1,ToLower_overhead ;if char stored in $t0 < 'a', skip
nop
bgtu $t0,$t2,ToLower_overhead ;if char stored in $t0 > 'z', skip
nop
ori $t0,$t0,0x20
sb $t0,($a0)
ToLower_overhead:
addiu $a0,1
b ToLower_again
nop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
li $t1,'A'
li $t2,'Z'
lbu $t0,($a0)
nop
beqz $t0,ToggleCase_done
nop
bltu $t0,$t1,ToggleCase_next
nop
bleu $t0,$t2,ToggleCase_Xor
nop
ToggleCase_next:
addiu $t1,0x20 ;li $t1,'a'
addiu $t2,0x20 ;li $t2,'z'
bltu $t0,$t1,ToggleCase_overhead
nop
bgtu $t0,$t2,ToggleCase_overhead
nop
ToggleCase_Xor:
xori $t0,$t0,0x20
sb $t0,($a0)
ToggleCase_overhead:
addiu $a0,1
b ToggleCase
nop
ToggleCase_done:
jr ra
nop
- Output:
alphaBETA ;original ALPHABETA ;uppercase alphabeta ;lowercase ALPHAbeta ;toggled
mIRC Scripting Language
echo -ag $upper(alphaBETA)
echo -ag $lower(alphaBETA)
Modula-3
MODULE TextCase EXPORTS Main;
IMPORT IO, Text, ASCII;
PROCEDURE Upper(txt: TEXT): TEXT =
VAR
len := Text.Length(txt);
res := "";
BEGIN
FOR i := 0 TO len - 1 DO
res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)]));
END;
RETURN res;
END Upper;
PROCEDURE Lower(txt: TEXT): TEXT =
VAR
len := Text.Length(txt);
res := "";
BEGIN
FOR i := 0 TO len - 1 DO
res := Text.Cat(res, Text.FromChar(ASCII.Lower[Text.GetChar(txt, i)]));
END;
RETURN res;
END Lower;
BEGIN
IO.Put(Upper("alphaBETA\n"));
IO.Put(Lower("alphaBETA\n"));
END TextCase.
Output:
ALPHABETA alphabeta
MUMPS
STRCASE(S)
SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SET LO="abcdefghijklmnopqrstuvwxyz"
WRITE !,"Given: "_S
WRITE !,"Upper: "_$TRANSLATE(S,LO,UP)
WRITE !,"Lower: "_$TRANSLATE(S,UP,LO)
QUIT
Output:
USER>DO STRCASE^ROSETTA("alphaBETA") Given: alphaBETA Upper: ALPHABETA Lower: alphabeta
Nanoquery
string = "alphaBETA"
println upper(string)
println lower(string)
Nemerle
using System.Console;
using System.Globalization;
module StringCase
{
Main() : void
{
def alpha = "alphaBETA";
WriteLine(alpha.ToUpper());
WriteLine(alpha.ToLower());
WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
}
}
NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols
abc = 'alphaBETA'
say abc.upper
say abc.lower
say abc.upper(1, 1) -- capitalize 1st character
NewLISP
(upper-case "alphaBETA")
(lower-case "alphaBETA")
Nial
toupper 'alphaBETA'
=ALPHABETA
tolower 'alphaBETA'
=alphabeta
Nim
In the following example, we use the ASCII version of the procedures to convert to lower case, to convert to upper case or to capitalize. In module “unicode” there exists also three procedures "toLower", "toUpper" and "capitalize" which can do the same thing for UTF-8 encoded strings.
import strutils
var s: string = "alphaBETA_123"
echo s, " as upper case: ", toUpperAscii(s)
echo s, " as lower case: ", toLowerAscii(s)
echo s, " as capitalized: ", capitalizeAscii(s)
echo s, " as normal case: ", normalize(s) # to lower case without underscores.
- Output:
alphaBETA_123 as upper case: ALPHABETA_123 alphaBETA_123 as lower case: alphabeta_123 alphaBETA_123 as capitalized: AlphaBETA_123 alphaBETA_123 as normal case: alphabeta123
Even with the Unicode specialized procedure, Nim doesn't handle all character correctly. For example, it fails for some characters like ß where it hasn't changed ß
into SS
(expected STROSSBÙRRI
)[2].
import unicode
var a: string = "Stroßbùrri"
var b: string = "ĥåçýджк"
echo a.toUpper
echo b.toUpper
- Output:
STROßBÙRRI ĤÅÇÝДЖК
Objeck
string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();
Objective-C
NSLog(@"%@", @"alphaBETA".uppercaseString);
NSLog(@"%@", @"alphaBETA".lowercaseString);
NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"
OCaml
let () =
let str = "alphaBETA" in
print_endline (String.uppercase_ascii str); (* ALPHABETA *)
print_endline (String.lowercase_ascii str); (* alphabeta *)
print_endline (String.capitalize_ascii str); (* AlphaBETA *)
;;
Octave
s = "alphaBETA";
slc = tolower(s);
suc = toupper(s);
disp(slc);
disp(suc);
Oforth
"alphaBETA" toUpper
"alphaBETA" toLower
OpenEdge/Progress
caps("alphaBETA")
lc("alphaBETA")
Oz
Convert to upper/lower-case:
declare
Str = "alphaBETA"
in
{System.showInfo {Map Str Char.toUpper}}
{System.showInfo {Map Str Char.toLower}}
Capitalize:
declare
[StringX] = {Link ['x-oz://system/String.ozf']}
in
{System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA"
Pascal
// Uppercase and Lowercase functions for a minimal standard Pascal
// where no library routines for these operations exist
PROGRAM upperlower;
// convert a character to uppercase
FUNCTION uch(ch: CHAR): CHAR;
BEGIN
uch := ch;
IF ch IN ['a'..'z'] THEN
uch := chr(ord(ch) AND $5F);
END;
// convert a character to lowercase
FUNCTION lch(ch: CHAR): CHAR;
BEGIN
lch := ch;
IF ch IN ['A'..'Z'] THEN
lch := chr(ord(ch) OR $20);
END;
// toggle uper/lower case character
FUNCTION ulch(ch: CHAR): CHAR;
BEGIN
ulch := ch;
IF ch IN ['a'..'z'] THEN ulch := uch(ch);
IF ch IN ['A'..'Z'] THEN ulch := lch(ch);
END;
// convert a string to uppercase
FUNCTION ucase(str: STRING): STRING;
var i: Integer;
BEGIN
ucase := '';
FOR i := 1 TO Length(str) DO
ucase := ucase + uch(str[i]);
END;
// convert a string to lowercase
FUNCTION lcase(str: STRING): STRING;
var i: Integer;
BEGIN
lcase := '';
FOR i := 1 TO Length(str) DO
lcase := lcase + lch(str[i]);
END;
// reverse cases in a given string
FUNCTION ulcase(str: STRING): STRING;
var i: Integer;
BEGIN
ulcase := '';
FOR i := 1 TO Length(str) DO
ulcase := ulcase + ulch(str[i]);
END;
VAR
ab : STRING = 'alphaBETA';
BEGIN
// demonstration
Writeln('Original string : ',ab);
Writeln('Reversed case : ',ulcase(ab));
Writeln('Upper case : ',ucase(ab));
Writeln('Lower case : ',lcase(ab));
END.
Demonstration:
Original string : alphaBETA Reversed case : ALPHAbeta Upper case : ALPHABETA Lower case : alphabeta
PascalABC.NET
##
var s := 'exAmpLe sTrinG';
s.ToLower.Println;
s.ToUpper.Println;
- Output:
example string EXAMPLE STRING
Peloton
Iterating through the peerset
<@ ENU$$$LSTPSTLITLIT>UPP|
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@>
<@ SAY&&&LIT>alphaBETA</@>
</@>
Same code in padded-out, variable-length English dialect
<# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP|
[<# SAY ELEMENT LIST>...</#>] <# SAY HELP ELEMENT LIST>...</#><# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|...</#>
<# SAY SUPERMACRO LITERAL>alphaBETA</#>
</#>
Output.
[FLC] 410400001 Flip case (410400001) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] ALPHAbeta [LOW] 410400002 Lower case (410400002) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] alphabeta [PRP] 410400003 Proper Case (410400003) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] Alphabeta [SNT] 410400004 Sentence case (410400004) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] Alphabeta [UPP] 410400005 Upper case (410400005) [Transformers^Abstract type transforms^Text transformers^Platform relative encoding and encrypting] ALPHABETA
Perl
my $string = "alphaBETA";
print uc($string), "\n"; # => "ALPHABETA"
print lc($string), "\n"; # => "alphabeta"
$string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta
print ucfirst($string), "\n"; # => "AlphaBETA"
print lcfirst("FOObar"), "\n"; # => "fOObar"
Also works in Perl 4 if the my is removed.
Phix
constant s = "alphaBETA" ?upper(s) ?lower(s)
There is also a bespoke convertCase function in demo\Edix\Edix.exw which accepts five operators: LOWER, UPPER, CAPITALISE, SENTENCE, and INVERT, which is obviously not part of the language, and a bit too long, messy, ugly, and unedifying, to bother reproducing here.
PHP
$str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Picat
main =>
S = "alphaBETA",
println(to_uppercase(S)),
println(to_lowercase(S)).
- Output:
ALPHABETA alphabeta
PicoLisp
(let Str "alphaBETA"
(prinl (uppc Str))
(prinl (lowc Str)) )
Pike
Note: String.Elite.elite_string has an element of randomness, so the output will differ from run to run.
string s = "alphaBETA";
string s2 = "foo bar gazonk";
write("Upper: %O\nLower: %O\nCapitalize: %O\nSilly: %O\nElite: %O\n",
upper_case(s),
lower_case(s),
String.capitalize(s),
String.sillycaps(s2),
String.Elite.elite_string(s2));
- Output:
Upper: "ALPHABETA" Lower: "alphabeta" Capitalize: "AlphaBETA" Silly: "Foo Bar Gazonk" Elite: "fo() 8ar 6azo|\\||<"
When dealing with Unicode (or any other supported encoding) care must be taken primarily in the output step to serialize the Unicode string into something the sink can handle. IO functions will throw an error if sent raw wide strings.
#charset utf8
void main()
{
string s = upper_case("ἀρχῇ ß");
string out = sprintf("Upper: %s\nLower: %s\n",
s, lower_case(s));
write( string_to_utf8(out) );
}
- Output:
Upper: ἈΡΧῇ ß Lower: ἀρχῇ ß
PL/I
declare s character (20) varying initial ('alphaBETA');
put skip list (uppercase(s));
put skip list (lowercase(s));
/* An alternative to the above, which might be used if some */
/* non-standard conversion is required, is shown for */
/* converting to upper case: */
put skip list ( translate(s, 'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') );
PL/SQL
declare
vc VARCHAR2(40) := 'alphaBETA';
ivc VARCHAR2(40);
lvc VARCHAR2(40);
uvc VARCHAR2(40);
begin
ivc := INITCAP(vc); -- 'Alphabeta'
lvc := LOWER(vc); -- 'alphabeta'
uvc := UPPER(vc); -- 'ALPHABETA'
end;
Plain English
To run:
Start up.
Put "alphaBeta" into a string.
Uppercase the string.
Write the string to the console.
Lowercase the string.
Write the string to the console.
Capitalize the string.
Write the string to the console.
Wait for the escape key.
Shut down.
- Output:
ALPHABETA alphabeta Alphabeta
Pop11
lvars str = 'alphaBETA';
lowertoupper(str) =>
uppertolower(str) =>
Potion
lowercase = (str) :
low = ("")
str length times (i) :
low append(if (65 <= str(i) ord and str(i) ord <= 90) :
"abcdefghijklmnopqrstuvwxyz"(str(i) ord - 65)
. else :
str(i)
.)
.
low join("")
.
uppercase = (str) :
upp = ("")
str length times (i) :
upp append(if (97 <= str(i) ord and str(i) ord <= 122) :
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"(str(i) ord - 97)
. else :
str(i)
.)
.
upp join("")
.
lowercase("alphaBETA") print
uppercase("alphaBETA") print
Powerbuilder
string ls_string
ls_string = 'alphaBETA'
ls_string = Upper(ls_string)
ls_string = Lower(ls_string)
PowerShell
$string = 'alphaBETA'
$lower = $string.ToLower()
$upper = $string.ToUpper()
$title = (Get-Culture).TextInfo.ToTitleCase($string)
$lower, $upper, $title
- Output:
alphabeta ALPHABETA Alphabeta
Python
s = "alphaBETA"
print s.upper() # => "ALPHABETA"
print s.lower() # => "alphabeta"
print s.swapcase() # => "ALPHAbeta"
print "fOo bAR".capitalize() # => "Foo bar"
print "fOo bAR".title() # => "Foo Bar"
import string
print string.capwords("fOo bAR") # => "Foo Bar"
string.capwords() allows the user to define word separators, and by default behaves slightly differently than title().
print "foo's bar".title() # => "Foo'S Bar"
print string.capwords("foo's bar") # => "Foo's Bar"
QB64
DIM s AS STRING * 9
s = "alphaBETA"
PRINT "The original string: " + s
PRINT ""
PRINT "Translated to lowercase: " + LCASE$(s)
PRINT "Translated to uppercase: " + UCASE$(s)
Optimized version:
CBTJD: 2020/03/13
- String does not have to be defined with a specific length using DIM.
- Addding the string identifier ($) to the variable is sufficient.
- PRINT does not need empty quotes to print a blank line.
- Semi-colons use less data than the concatenation (+) method.
s$ = "alphaBETA"
PRINT "The original string: "; s$: PRINT
PRINT "Converted to lowercase: "; LCASE$(s$)
PRINT "Converted to uppercase: "; UCASE$(s$)
Quackery
[ $ "" swap
witheach [ upper join ] ] is upper$ ( $ --> $ )
[ $ "" swap
witheach [ lower join ] ] is lower$ ( $ --> $ )
$ "PaTrIcK, I dOn'T tHiNk WuMbO iS a ReAl wOrD."
dup lower$ echo$ cr
upper$ echo$ cr
- Output:
patrick, i don't think wumbo is a real word. PATRICK, I DON'T THINK WUMBO IS A REAL WORD.
R
str <- "alphaBETA"
toupper(str)
tolower(str)
Racket
#lang racket
(define example "alphaBETA")
(string-upcase example)
;"ALPHABETA"
(string-downcase example)
;"alphabeta"
(string-titlecase example)
;"Alphabeta"
Raku
(formerly Perl 6) In Raku, case modification is implemented as builtin subroutine or method:
my $word = "alpha BETA" ;
say uc $word; # all uppercase (subroutine call)
say $word.uc; # all uppercase (method call)
# from now on we use only method calls as examples
say $word.lc; # all lowercase
say $word.tc; # first letter titlecase
say $word.tclc; # first letter titlecase, rest lowercase
say $word.wordcase; # capitalize each word
Output:
ALPHA BETA alpha beta Alpha BETA Alpha beta Alpha Beta
Raven
'alphaBETA' upper
'alhpaBETA' lower
REBOL
print ["Original: " original: "alphaBETA"]
print ["Uppercase:" uppercase original]
print ["Lowercase:" lowercase original]
Output:
Original: alphaBETA Uppercase: ALPHABETA Lowercase: alphabeta
Red
str: "alphaBETA"
>> uppercase str
== "ALPHABETA"
>> lowercase str
== "alphabeta"
>> uppercase/part str 5
== "ALPHAbeta"
Retro
'alphaBETA s:to-upper s:put
'alphaBETA s:to-lower s:put
REXX
with TRANSLATE BIF
The following code will execute correctly in ASCII and EBCDIC.
abc = "abcdefghijklmnopqrstuvwxyz" /*define all lowercase Latin letters.*/
abcU = translate(abc) /* " " uppercase " " */
x = 'alphaBETA' /*define a string to a REXX variable. */
y = translate(x) /*uppercase X and store it ───► Y */
z = translate(x, abc, abcU) /*translate uppercase──►lowercase chars*/
with PARSE UPPER & PARSE LOWER statements
The following code will execute correctly in ASCII and EBCDIC.
x = "alphaBETA" /*define a string to a REXX variable. */
parse upper var x y /*uppercase X and store it ───► Y */
parse lower var x z /*lowercase X " " " ───► Z */
/*Some REXXes don't support the LOWER option for the PARSE command.*/
with UPPER & LOWER BIFs
The following code will execute correctly in ASCII and EBCDIC.
x = 'alphaBETA' /*define a string to a REXX variable. */
y = upper(x) /*uppercase X and store it ───► Y */
z = lower(x) /*lowercase X " " " ───► Z */
/*Some REXXes don't support the UPPER and LOWER BIFs (built-in functions).*/
with UPPER statement
The following code will execute correctly in ASCII and EBCDIC.
x = "alphaBETA" /*define a string to a REXX variable. */
y=x; upper y /*uppercase X and store it ───► Y */
parse lower var x z /*lowercase Y " " " ───► Z */
/*Some REXXes don't support the LOWER option for the PARSE command.*/
with capitalized words
The following code will execute correctly in ASCII and EBCDIC.
/*REXX program capitalizes each word in string, and maintains imbedded blanks. */
x= "alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh",
"ayin pe tzadi qof resh shin tav." /*the "old" spelling of Hebrew letters.*/
y= capitalize(x) /*capitalize each word in the string. */
say x /*display the original string of words.*/
say y /* " " capitalized words.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
capitalize: procedure; parse arg z; $=' 'z /*prefix $ string with a blank. */
abc = "abcdefghijklmnopqrstuvwxyz" /*define all Latin lowercase letters.*/
do j=1 for 26 /*process each letter in the alphabet. */
_=' 'substr(abc,j,1); _U=_ /*get a lowercase (Latin) letter. */
upper _U /* " " uppercase " " */
$=changestr(_, $, _U) /*maybe capitalize some word(s). */
end /*j*/
return substr($, 2) /*return the capitalized words. */
Some older REXXes don't have a changestr BIF, so one is included here ───► CHANGESTR.REX.
- output:
alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh ayin pe tzadi qof resh shin tav. Alef Bet Gimel Dalet He Vav Zayin Het Tet Yod Kaf Lamed Mem Nun Samekh Ayin Pe Tzadi Qof Resh Shin Tav.
Note: there are many variant spellings of the Hebrew alphabet.
with case swap
The following code will execute correctly in ASCII and EBCDIC.
/*REXX program swaps the letter case of a string: lower ──► upper & upper ──► lower.*/
abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters. */
abcU = translate(abc) /* " " " uppercase " */
x = 'alphaBETA' /*define a string to a REXX variable. */
y = translate(x, abc || abcU, abcU || abc) /*swap case of X and store it ───► Y */
say x
say y
/*stick a fork in it, we're all done. */
output
alphaBETA ALPHAbeta
version 2
x='alphaBETA'; Say ' x='||x
Say 'three ways to uppercase'
u1=translate(x); Say ' u1='u1
u2=upper(x); Say ' u2='u2
parse upper var x u3; Say ' u3='u3
abc ='abcdefghijklmnopqrstuvwxyz'
abcu=translate(abc); Say 'three ways to lowercase'
l1=translate(x,abc,abcu); Say ' l1='l1
l2=lower(x); Say ' l2='l2
parse lower var x l3; Say ' l3='l3
- Note: Parse options upper and lower not available in every Rexx
- Builtin functions upper and lower not available in every Rexx
- Upper instruction not available in ooRexx
For German input (considering umlaute) these will uppercase them:
uppercase: /*courtesy Gerard Schildberger */
return translate(changestr("ß",translate(arg(1),'ÄÖÜ',"äöü"),'SS'))
uppercase2: Procedure
Parse Arg a
a=translate(arg(1),'ÄÖÜ',"äöü") /* translate lowercase umlaute */
a=changestr("ß",a,'SS') /* replace ß with SS */
return translate(a) /* translate lowercase letters */
Translation to lowercase is not similarly possible because of 'SS'->'ß' or -> 'ss' ??
Note: Recently an uppercase ß was introduced in Austria. I haven't used it yet.
Ring
aString = "WELCOME TO THE ring programming language"
see lower(aString) + nl
see upper(aString) + nl
RPL
≪ 1 OVER SIZE FOR j DUP j DUP SUB IF DUP "a" < OVER "z" > OR THEN DROP ELSE NUM 32 - CHR j SWAP REPL END NEXT ≫ ≫ '→UPPER' STO ≪ 1 OVER SIZE FOR j DUP j DUP SUB IF DUP "A" < OVER "Z" > OR THEN DROP ELSE NUM 32 + CHR j SWAP REPL END NEXT ≫ ≫ '→LOWER' STO
"alphaBETA" →UPPER "alphaBETA" →LOWER
- Output:
2: "ALPHABETA" 1: "alphabeta"
Ruby
"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"
"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".capitalize # => "Alphabeta"
These methods used to affect ASCII letters A-Z and a-z only. From Ruby 2.4 onward however, these methods support Full Unicode case mapping, suitable for most languages, by default. (Options can be specified for Turkic, Lithuanian and ascii)
'ĥåçýджк'.upcase # => "ĤÅÇÝДЖК"
Rust
fn main() {
println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño
}
Scala
val s="alphaBETA"
println(s.toUpperCase) //-> ALPHABETA
println(s.toLowerCase) //-> alphabeta
println(s.capitalize) //-> AlphaBETA
println(s.reverse) //-> ATEBahpla
Scheme
(define s "alphaBETA")
(list->string (map char-upcase (string->list s)))
(list->string (map char-downcase (string->list s)))
Using SRFI-13:
> (define s "alphaBETA gammaDELTA")
> (string-upcase s) ;; turn all into upper case
"ALPHABETA GAMMADELTA"
> (string-downcase s) ;; turn all into lower case
"alphabeta gammadelta"
> (string-titlecase s) ;; capitalise start of each word
"Alphabeta Gammadelta"
Sed
Piping through sed in bash:
echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
Other functions:
# Invert case
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/'
GNU sed supports special sequences to change case:
# to uppercase
$ echo alphaBETA | sed 's/.*/\U&/'
ALPHABETA
# to lowercase
$ echo alphaBETA | sed 's/.*/\L&/'
alphabeta
Seed7
writeln(upper("alphaBETA")); writeln(lower("alphaBETA"));
SenseTalk
set letters to "alphaBETA"
put lowercase of letters // alphabeta
put uppercase of letters // ALPHABETA
put capitalized of letters // Alphabeta
repeat with each character of letters by reference
if it is an uppercase
set it to lowercase of it
else
set it to uppercase of it
end if
end repeat
put letters //ALPHAbeta
Sidef
say "alphaBETA".lc; #=> alphabeta
say "alphaBETA".uc; #=> ALPHABETA
say "alphaBETA".tc; #=> AlphaBETA
say "alpha BETA".wc; #=> Alpha Beta
say "alpha BETA".tc; #=> Alpha BETA
say "alpha BETA".tclc; #=> Alpha beta
Simula
TEXT soup, lower;
soup :- "alphaBETA";
lower :- LOWCASE(COPY(soup)); ! COPY, else soup is changed;
OutText("upper: "); OutText(UPCASE("alphaBETA"));
OutText(", lower: "); OutText(lower);
OutText(", soup: "); OutText(soup); Outimage;
Slate
'alphaBETA' toLowercase.
'alphaBETA' toUppercase.
Smalltalk
'ALPHAbeta' asUppercase "->'ALPHABETA' "
'ALPHAbeta' asLowercase "-> 'alphabeta' "
'alphabeta' asUppercaseFirst "-> 'Alphabeta' "
Unicode (notice, that this cannot be done simply with a straight forward "ch := ch -$a + $A" loop):
(may work with other dialects too, but I have not verified)
'αβγω' asUppercase -> 'ΑΒΓΩ'
'ĥåçýджк' asUppercase "-> 'ĤÅÇÝДЖК'
'abcäöüáéíýıijńǵȅȇȉ' asUppercase -> 'ABCÄÖÜÁÉÍÝIIJŃǴȄȆȈ'
SNOBOL4
There are no standard Snobol libraries or case conversion built-ins. But case functions are easy to roll using the character class keywords. Native charset only.
define('uc(str)') :(uc_end)
uc uc = replace(str,&lcase,&ucase) :(return)
uc_end
define('lc(str)') :(lc_end)
lc lc = replace(str,&ucase,&lcase) :(return)
lc_end
define('ucfirst(str)ch') :(ucfirst_end)
ucfirst str len(1) . ch = uc(ch)
ucfirst = str :(return)
ucfirst_end
define('swapc(str)') :(swapc_end)
swapc str = replace(str,&ucase &lcase, &lcase &ucase)
swapc = str :(return)
swapc_end
* # Test and display
str = 'alphaBETA'
output = str
output = lc(str)
output = uc(str)
output = ucfirst(str)
output = swapc(str)
end
An alternative way of constructing the above that groups related functions together in a denser display:
define('UC(STR)')
define('LC(STR)')
define('UCFIRST(STR)')
define('SWAPC(STR)') :(CASES.END)
UC uc = replace(str,&lcase,&ucase) :(RETURN)
LC lc = replace(str,&ucase,&lcase) :(RETURN)
UCFIRST str len(1) . ch = uc(ch) ; ucfirst = str :(RETURN)
SWAPC swapc = replace(str, &ucase &lcase, &lcase &ucase) :(RETURN)
CASES.END
* # Test and display
str = 'alphaBETA'
output = str
output = lc(str)
output = uc(str)
output = ucfirst(str)
output = swapc(str)
END
Output:
alphaBETA alphabeta ALPHABETA AlphaBETA ALPHAbeta
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "stringcase" )
@( description, "Take the string 'alphaBETA', and demonstrate how to" )
@( description, "convert it to UPPER-CASE and lower-case. Use the" )
@( description, "default encoding of a string literal or plain ASCII if" )
@( description, "there is no string literal in your language. Show any" )
@( description, "additional case conversion functions (e.g. swapping" )
@( description, "case, capitalizing the first letter, etc.) that may be" )
@( description, "included in the library of your language. " )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/String_case" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure stringcase is
s : constant string := "alphaBETA";
begin
? strings.to_upper( s );
? strings.to_lower( s );
? strings.to_proper( s );
end stringcase;
SQL
declare @s varchar(10)
set @s = 'alphaBETA'
print upper(@s)
print lower(@s)
SQL PL
With SQL only:
values upper('alphaBETA');
values lower('alphaBETA');
values initcap('alphaBETA');
-- Within a SQL query.
select upper('alphaBETA') from sysibm.sysdummy1;
Output:
db2 -t db2 => values upper('alphaBETA'); 1 --------- ALPHABETA 1 record(s) selected. db2 => values lower('alphaBETA'); 1 --------- alphabeta 1 record(s) selected. db2 => values initcap('alphaBETA'); 1 --------- Alphabeta 1 record(s) selected. db2 => select upper('alphaBETA') from sysibm.sysdummy1; 1 --------- ALPHABETA 1 record(s) selected.
Standard ML
val strupr = String.map Char.toUpper;
val strlwr = String.map Char.toLower;
Test
- strupr "alphaBETA"; val it = "ALPHABETA" : string - strlwr "alphaBETA"; val it = "alphabeta" : string
Stata
Use strupper and strlower to change case of ASCII characters. Use ustrupper and ustrlower to change case of all Unicode letters.
. scalar s="alphaBETA"
. di strupper(s)
ALPHABETA
. di strlower(s)
alphabeta
Notice there may be some difficulties with Unicode characters. In the following, the uppercase sigma is correctly converted back to the lowercase variant, but the iota subscript is not.
. scalar a="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. scalar b=ustrupper(a)
. di b
ἘΝ ἈΡΧΗ͂Ι ἘΠΟΊΗΣΕΝ Ὁ ΘΕῸΣ ΤῸΝ ΟΥ̓ΡΑΝῸΝ ΚΑῚ ΤῊΝ ΓΗ͂Ν
. di ustrlower(b)
ἐν ἀρχῆι ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν
Swift
import Foundation
println("alphaBETA".uppercaseString)
println("alphaBETA".lowercaseString)
println("foO BAr".capitalizedString)
- Output:
ALPHABETA alphabeta Foo Bar
Tcl
set string alphaBETA
# three built-in case conversion commands
string toupper $string ;# ==> ALPHABETA
string tolower $string ;# ==> alphabeta
string totitle $string ;# ==> Alphabeta
# not built-in
proc swapcase {s} {
foreach char [split $s ""] {
if {$char eq [set CHAR [string toupper $char]]} {
append new [string tolower $char]
} else {
append new $CHAR
}
}
return $new
}
swapcase $string ;# ==> ALPHAbeta
# better performance, but English alphabet only
proc swapcase_en {s} {
string map {
a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z
A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z
} $s
}
swapcase Père ;# ==> pÈRE
swapcase_en Père ;# ==> pèRE
Toka
needs ctype [ i 1 - ] is i [ string.getLength 0 [ dup i + c@ toupper over i + c! ] countedLoop ] is string.toUpper [ string.getLength 0 [ dup i + c@ tolower over i + c! ] countedLoop ] is string.toLower " alphaBETA" string.toUpper type cr " alphaBETA" string.toLower type cr
TorqueScript
$string = "alphaBETA"; $upperCase = strUpr($string); $lowerCase = strLwr($string);
Transd
#lang transd
MainModule: {
_start: (λ
(with s "alphaBETA"
(lout (toupper s))
(lout (tolower s)))
)
}
- Output:
ALPHABETA alphabeta
TUSCRIPT
$$ MODE TUSCRIPT,{}
string="alphaBETA"
lowercase =EXCHANGE(string," {&a} {-0-} ")
uppercase1=EXCHANGE(string," {&a} {-0+} ")
uppercase2=CAPS (string)
PRINT lowercase
PRINT uppercase1
PRINT uppercase2
Output:
alphabeta ALPHABETA ALPHABETA
Uiua
¯"alphaBETA" # swapcase
⌵"alphaBETA" # upper
¯⌵"alphaBETA" # lower
±"alphaBETA123" # case mask 1=upper, -1=lower, 0=neither
- Output:
"ALPHAbeta" "ALPHABETA" "alphabeta" [¯1 ¯1 ¯1 ¯1 ¯1 1 1 1 1 0 0 0]
UNIX Shell
For System V tr:
echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA
echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta
For BSD tr, GNU tr, or any POSIX system:
echo alphaBETA | tr a-z A-Z # => ALPHABETA
echo alphaBETA | tr A-Z a-z # => alphabeta
System V has a different syntax, and requires square brackets around ranges. Portable scripts can use System V syntax; the other systems handle square brackets as literal characters, translating [ to [ and ] to ], which is harmless.
Bash
s="alphaBETA"
echo ${s^^} # => ALPHABETA
echo ${s,,} # => alphabeta
echo ${s^} # => AlphaBETA
Z Shell
s="alphaBETA"
echo ${s:u} # => ALPHABETA
echo ${s:l} # => alphabeta
Ursa
out (lower "alphaBETA") endl console
out (upper "alphaBETA") endl console
Ursala
Case conversion functions aren't built in but can be defined using the reification operator (-:) to construct a function from a list of pairs.
#import std
to_upper = * -:~& ~=`A-~p letters
to_lower = * -:~& ~=`A-~rlp letters
#show+
examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'>
output:
ALPHABETA alphabeta
Vala
string s = "alphaBeta";
// stores ALPHABETA to string
string s_upper = s.up();
// stores alphabeta to string
string s_lower = s.down();
VBA
Function StringCase()
Dim s As String
s = "alphaBETA"
Debug.Print UCase(s)
Debug.Print LCase(s)
Debug.Print WorksheetFunction.Proper(s)
End Function
Output:
ALPHABETA alphabeta Alphabeta
VBScript
Dim MyWord
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA") ' Returns "alphabeta"
Vedit macro language
#1 = CP
IT("alphaBETA")
Case_Upper_Block(#1, CP)
Case_Lower_Block(#1, CP)
V (Vlang)
fn show(s string) {
println('string: $s len: $s.len')
println('All upper case: ${s.to_upper()}')
println('All lower case: ${s.to_lower()}')
println('Title words: ${s.title()}')
println('')
}
fn main(){
show('alphaBETA')
show('alpha BETA')
show('DŽLjnj')
show("o'hare O'HARE o’hare don't")
}
Output:
string: alphaBETA len: 9 All upper case: ALPHABETA All lower case: alphabeta Title words: AlphaBETA string: alpha BETA len: 10 All upper case: ALPHA BETA All lower case: alpha beta Title words: Alpha BETA string: DŽLjnj len: 6 All upper case: DŽLjnj All lower case: DŽLjnj Title words: DŽLjnj string: o'hare O'HARE o’hare don't len: 28 All upper case: O'HARE O'HARE O’HARE DON'T All lower case: o'hare o'hare o’hare don't Title words: O'hare O'HARE O’hare Don't
Wren
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).
import "./str" for Str, Utf8
var strs = ["alphaBETA", "ação", "o'hare O'HARE o’hare don't"]
System.print("Using 'Str' class methods:")
for (s in strs) {
System.print(" original : %(s)")
System.print(" lower : %(Str.lower(s))")
System.print(" upper : %(Str.upper(s))")
System.print(" capitalize : %(Str.capitalize(s))")
System.print(" title : %(Str.title(s))")
System.print(" swapCase : %(Str.swapCase(s))")
System.print()
}
var strs2 = ["Stroßbùrri", "ĥåçýджк", "DŽLjnj"]
System.print("Using 'Utf8' class methods:")
for (s in strs2) {
System.print(" original : %(s)")
System.print(" lower : %(Utf8.lower(s))")
System.print(" upper : %(Utf8.upper(s))")
System.print(" capitalize : %(Utf8.capitalize(s))")
System.print(" title : %(Utf8.title(s))")
System.print()
}
- Output:
Using 'Str' class methods: original : alphaBETA lower : alphabeta upper : ALPHABETA capitalize : AlphaBETA title : AlphaBETA swapCase : ALPHAbeta original : ação lower : ação upper : AÇÃO capitalize : Ação title : Ação swapCase : AÇÃO original : o'hare O'HARE o’hare don't lower : o'hare o'hare o’hare don't upper : O'HARE O'HARE O’HARE DON'T capitalize : O'hare O'HARE o’hare don't title : O'hare O'HARE O’hare Don't swapCase : O'HARE o'hare O’HARE DON'T Using 'Utf8' class methods: original : Stroßbùrri lower : stroßbùrri upper : STROẞBÙRRI capitalize : Stroßbùrri title : Stroßbùrri original : ĥåçýджк lower : ĥåçýджк upper : ĤÅÇÝДЖК capitalize : Ĥåçýджк title : Ĥåçýджк original : DŽLjnj lower : džljnj upper : DŽLJNJ capitalize : DžLjnj title : DžLjnj
XPL0
string 0; \use zero-terminated string convention
include c:\cxpl\stdlib; \ToUpper, ToLower, and 'code' declarations
proc StrToUpper(S); \Convert string to uppercase characters
char S;
while S(0) do [S(0):= ToUpper(S(0)); S:=S+1];
proc StrToLower(S); \Convert string to lowercase characters
char S;
while S(0) do [S(0):= ToLower(S(0)); S:=S+1];
char Str;
[Str:= "alphaBETA";
StrToUpper(Str);
Text(0, Str); CrLf(0);
StrToLower(Str);
Text(0, Str); CrLf(0);
]
Output:
ALPHABETA alphabeta
Z80 Assembly
The English alphabet is a subset of the ASCII character set, and the upper and lower case letters are 32 bytes apart. Bit 5 "toggles" the case of any letter in this range. Assuming your string exists in RAM, these subroutines are all that is needed to switch the string from upper to lower case, and vice versa. The first two functions are destructive, meaning that you cannot recover the original string after using them. The ToggleCase
function can be performed twice on the same string to get the original string back.
ToUpperCase:
;INPUT:
;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
;OVERWRITES THE STRING YOU INPUT WITH THE UPPERCASE VERSION
ld bc,&617A ;lower case ascii range
loop_toUpperCase:
ld a,(hl)
or a
ret z
call CompareRange_Inclusive ;is this a lower case letter?
jr c,skipUpperCase ;if not, don't change it!
and %11011111 ;change to upper case
ld (hl),a ;store back in string
skipUpperCase:
inc hl
jr loop_toUpperCase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToLowerCase:
;INPUT:
;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
;OVERWRITES THE STRING YOU INPUT WITH THE LOWERCASE VERSION
ld bc,&415A ;upper case ascii range
loop_toLowerCase:
ld a,(hl)
or a
ret z
call CompareRange_Inclusive
jr c,skipLowerCase
or %00100000
ld (hl),a
skipLowerCase:
inc hl
jr loop_toLowerCase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
;INPUT:
;HL = BASE ADDRESS OF A NULL-TERMINATED STRING
;INVERTS THE CASE OF ALL ALPHABET CHARACTERS IN THE STRING
ld bc,&415A
loop_toggleCase:
ld a,(hl)
or a
ret z
call CompareRange_Inclusive
jr nc,toggle
push bc
ld bc,&617A
call CompareRange_Inclusive
pop bc
jr c, skipToggleCase
toggle:
xor %00100000
ld (hl),a
skipToggleCase:
inc hl
jr loop_toggleCase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CompareRange_Inclusive:
;returns CF CLEAR if B <= A <= C, and CF SET otherwise.
cp b
ret c ;if carry set, A < B thus out of range.
push de
ld e,a
ld a,c
ld c,e ;swap A with C
cp c ;compare C to A. Signs are reversed.
;if carry set, "A" < "C" which means original C < original A. Thus out of range.
;if carry clear, we are in range.
ld e,a ;now put A and C back where they belong.
ld a,c
ld c,e ;none of this affects the flags, so the compare is still valid.
pop de
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- Output:
ALPHABETA alphabeta ALPHAbeta
zkl
s:="alphaBETA";
s.toLower(); //--> "alphabeta"
s.toUpper(); //--> "ALPHABETA"
Zig
const std = @import("std");
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
const string = "alphaBETA";
var lower: [string.len]u8 = undefined;
var upper: [string.len]u8 = undefined;
for (string) |char, i| {
lower[i] = std.ascii.toLower(char);
upper[i] = std.ascii.toUpper(char);
}
try stdout_wr.print("lower: {s}\n", .{lower});
try stdout_wr.print("upper: {s}\n", .{upper});
// TODO use https://codeberg.org/dude_the_builder/zigstr
}
Zoea
program: uppercase
input: 'FOObar'
output: 'FOOBAR'
program: lowercase
input: 'FOObar'
output: 'foobar'
- Output:
ALPHABETA alphabeta
Zoea Visual
- Programming Tasks
- String manipulation
- 11l
- 360 Assembly
- 4D
- 6502 Assembly
- 68000 Assembly
- 8080 Assembly
- AArch64 Assembly
- Action!
- Action! Tool Kit
- ActionScript
- Ada
- ALGOL 68
- ALGOL W
- Amazing Hopper
- APL
- APL (Dyalog)
- AppleScript
- Arbre
- ARM Assembly
- Arturo
- AutoHotkey
- AutoIt
- Avail
- AWK
- BASIC
- Applesoft BASIC
- BASIC256
- BBC BASIC
- Chipmunk Basic
- Commodore BASIC
- FreeBASIC
- FutureBasic
- Gambas
- IS-BASIC
- Liberty BASIC
- PureBasic
- QBasic
- Run BASIC
- TI-83 BASIC
- True BASIC
- Visual Basic
- Visual Basic .NET
- XBasic
- Yabasic
- BCPL
- Beef
- Befunge
- BQN
- Bracmat
- Burlesque
- C
- C sharp
- C++
- STL
- Clojure
- CMake
- COBOL
- ColdFusion
- Common Lisp
- Component Pascal
- Crystal
- D
- Dart
- DBL
- Delphi
- Object Pascal
- DWScript
- Dyalect
- E
- EasyLang
- EchoLisp
- ECL
- Ecstasy
- Ed
- Elena
- Elixir
- Elm
- EMal
- Erlang
- Excel
- F Sharp
- Factor
- Falcon
- Fantom
- Forth
- Fortran
- Frink
- GAP
- GDScript
- GML
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Joy
- Jq
- Jsish
- Julia
- K
- Kotlin
- Lambdatalk
- Lang
- Lasso
- Lingo
- LiveCode
- Logo
- Lua
- M2000 Interpreter
- M4
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- MAXScript
- Mercury
- Metafont
- Min
- MiniScript
- MIPS Assembly
- MIRC Scripting Language
- Modula-3
- MUMPS
- Nanoquery
- Nemerle
- NetRexx
- NewLISP
- Nial
- Nim
- Objeck
- Objective-C
- OCaml
- Oforth
- OpenEdge/Progress
- Oz
- Pascal
- PascalABC.NET
- Peloton
- Perl
- Phix
- Phix/basics
- PHP
- Picat
- PicoLisp
- Pike
- PL/I
- PL/SQL
- Plain English
- Pop11
- Potion
- Powerbuilder
- PowerShell
- Python
- QB64
- Quackery
- R
- Racket
- Raku
- Raven
- REBOL
- Red
- Retro
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Sed
- Seed7
- SenseTalk
- Sidef
- Simula
- Slate
- Smalltalk
- SNOBOL4
- SparForte
- SQL
- SQL PL
- Standard ML
- Stata
- Swift
- Tcl
- Toka
- TorqueScript
- Transd
- TUSCRIPT
- Uiua
- UNIX Shell
- Ursa
- Ursala
- Vala
- VBA
- VBScript
- Vedit macro language
- V (Vlang)
- Wren
- Wren-str
- XPL0
- Z80 Assembly
- Zkl
- Openscad/Omit
- PARI/GP/Omit
- Zig
- Zoea
- Zoea Visual
- Encodings
- Pages with too many expensive parser function calls