Jump to content

String case

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

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

4D

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

ActionScript

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

Ada

<lang ada>with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Text_Io; use Ada.Text_Io;

procedure Upper_Case_String is

  S : String := "alphaBETA";

begin

  Put_Line(To_Upper(S));
  Put_Line(To_Lower(S));

end Upper_Case_String;</lang>

ALGOL 68

<lang algol68># Demonstrate toupper and tolower for standard ALGOL 68 strings. This does not work for multibyte character sets. #

PROC to upper = ( CHAR c )CHAR: (

 IF ABS "a" <= ABS c & ABS c <= ABS "z" THEN
    REPR ( ABS c - ABS "a" + ABS "A" )
 ELSE
    c
 FI

);

PROC to lower = ( CHAR c )CHAR: (

 IF ABS "A" <= ABS c & ABS c <= ABS "Z" THEN
    REPR ( ABS c - ABS "A" + ABS "a" )
 ELSE
    c
 FI

);

  1. upper-cases s in place #

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

   FOR i FROM LWB s TO UPB s DO
       s[i] := toupper(s[i])
   OD

);

  1. lower-cases s in place #

PROC str to lower = (REF STRING s)VOID : (

   FOR i FROM LWB s TO UPB s DO
       s[i] := tolower(s[i])
   OD

);

main: (

   STRING t := "alphaBETA";
   str to upper(t);
   printf(($"uppercase: "gl$, t));
   str to lower(t);
   printf(($"lowercase: "gl$, t))

)</lang>

APL

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

AutoHotkey

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

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

AWK

<lang awk>BEGIN {

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

}</lang>

BASIC

Works with: QuickBasic version 4.5

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

C

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

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

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

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

}


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

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

}

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

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

}</lang>

C++

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

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

<lang cpp>#include <algorithm>

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

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

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

}

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

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

}</lang>

Here is sample usage code:

<lang cpp>#include <iostream>

  1. include <string>

using namespace std; int main() {

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

}</lang>

C#

<lang csharp>string array = "alphaBETA"; System.Console.WriteLine(array.ToUpper()); System.Console.WriteLine(array.ToLower());</lang>

Clojure

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

ColdFusion

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

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

Common Lisp

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

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

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

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

D

<lang d>import tango.text.Unicode : toUpper, toLower; import tango.io.Stdout;

void main() {

   auto str = "alphaBETA";
   Stdout(str.toUpper()).newline;
   Stdout(str.toLower()).newline;

}</lang>

Delphi

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

E

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

Erlang

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

F#

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

Factor

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

Forth

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

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

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

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

Output:

alphaBETA
ALPHABETA
alphabeta

Fortran

Works with: Fortran version 90 and later

<lang fortran> program example

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

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

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

Groovy

<lang groovy>def str = 'alphaBETA'

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

Output:

ALPHABETA
alphabeta

Haskell

<lang haskell>import Data.Char

s = "alphaBETA"

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

IDL

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

J

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

  tolower 'alphaBETA'

alphabeta</lang>

or alternative definitions: <lang j>upper=: (a.,~a.{~65+i.26) {~ (a.,~a.{~97+i.26) i. ] lower=: (a.,~a.{~97+i.26) {~ (a.,~a.{~65+i.26) i. ] </lang>

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

  lower 'alphaBETA'

alphabeta</lang>

Java

<lang java>String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase());</lang>

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

JavaScript

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

Output:

ALPHABETA
alphabeta
Works with: NJS version 0.2.5

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

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

M4

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

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

Mathematica

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

 ALPHABETA
 alphabeta

MAXScript

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

Metafont

We need to implement it, since it is not already given; the following code works only for ASCII or ASCII based encodings. (It could work anyway also for single byte encodings where letters are contiguous).

<lang metafont>vardef isbetween(expr a, i, f) =

 if string a:
   if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)):
     true
   else:
     false
   fi
 else:
   false
 fi enddef;

vardef toupper(expr s) =

 save ?; string ?; ? := ""; d := ASCII"A" - ASCII"a";
 for i = 0 upto length(s)-1:
   if isbetween(substring(i, i+1) of s, "a", "z"):
     ? := ? & char(ASCII(substring(i,i+1) of s) + d)
   else:
     ? := ? & substring(i, i+1) of s
   fi;
 endfor
 ?

enddef;

vardef tolower(expr s) =

 save ?; string ?; ? := ""; d := ASCII"a" - ASCII"A";
 for i = 0 upto length(s)-1:
   if isbetween(substring(i, i+1) of s, "A", "Z"):
     ? := ? & char(ASCII(substring(i,i+1) of s) + d)
   else:
     ? := ? & substring(i, i+1) of s
   fi;
 endfor
 ?

enddef;</lang>

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

end</lang>

Modula-3

<lang modula3>MODULE TextCase EXPORTS Main;

IMPORT IO, Text, ASCII;

PROCEDURE Upper(txt: TEXT): TEXT =

 VAR
   len := Text.Length(txt);
   res := "";
 BEGIN
   FOR i := 0 TO len - 1 DO
     res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)]));
   END;
   RETURN res;
 END Upper;

PROCEDURE Lower(txt: TEXT): TEXT =

 VAR
   len := Text.Length(txt);
   res := "";
 BEGIN
   FOR i := 0 TO len - 1 DO
     res := Text.Cat(res, Text.FromChar(ASCII.Lower[Text.GetChar(txt, i)]));
   END;
   RETURN res;
 END Lower;

BEGIN

 IO.Put(Upper("alphaBETA\n"));
 IO.Put(Lower("alphaBETA\n"));

END TextCase.</lang> Output:

ALPHABETA
alphabeta

Nial

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

Objective-C

Works with: GNUstep
Works with: Cocoa

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

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

OCaml

<lang ocaml>let () =

 let str = "alphaBETA" in
 print_endline (String.uppercase str); (* ALPHABETA *)
 print_endline (String.lowercase str); (* alphabeta *)
 print_endline (String.capitalize str); (* AlphaBETA *)
</lang>

Octave

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

Oz

<lang oz>declare

 fun {SwapCase Ch}
   if {Char.isUpper Ch} then {Char.toLower Ch}
   elseif {Char.isLower Ch} then {Char.toUpper Ch}
   else Ch end
 end

 Str = "alphaBETA"

in

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

OpenEdge/Progress

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

Perl

Works with: Perl version 5.x

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

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

Also works in Perl 4 if the my is removed.

Works with: Perl version 6

<lang perl>my $string = "alphaBETA"; say $string.uc say $string.lc</lang>

PHP

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

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

PicoLisp

<lang PicoLisp>(let Str "alphaBETA"

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

PL/I

<lang PL/I> declare s character (20) varying initial ('alphaBETA');

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

<lang PL/I> /* An alternative to the above, which might be used if some */ /* non-standard conversion is required, is shown for */ /* converting to upper case: */ put skip list ( translate(s, 'abcdefghijklmnopqrstuvwxyz',

                            'ABCDEFGHIJKLMNOPQRSTUVWXYZ') );

</lang>

PL/SQL

<lang plsql>declare

   vc  VARCHAR2(40) := 'alphaBETA';
   ivc VARCHAR2(40);
   lvc VARCHAR2(40);
   uvc VARCHAR2(40);

begin

   ivc := INITCAP(vc); -- 'Alphabeta'
   lvc := LOWER(vc);   -- 'alphabeta'
   uvc := UPPER(vc);   -- 'ALPHABETA'

end; </lang>

Pop11

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

PowerShell

<lang powershell>$string = 'alphaBETA' $lower = $string.ToLower() $upper = $string.ToUpper()</lang>

PureBasic

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

Python

<lang python>s = "alphaBETA" print s.upper() # => "ALPHABETA" print s.lower() # => "alphabeta"

print s.swapcase() # => "ALPHAbeta" print s.capitalize() # => "Alphabeta"

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

R

<lang R> str <- "alphaBETA"

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

Raven

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

REBOL

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

Output:

Original:  alphaBETA
Uppercase: ALPHABETA
Lowercase: alphabeta

Ruby

Works with: Ruby version 1.8

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

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

Scheme

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

Seed7

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

Slate

<lang slate>'alphaBETA' toLowercase.

'alphaBETA' toUppercase.</lang>

Smalltalk

<lang smalltalk>'ALPHAbeta' asUppercase. 'ALPHAbeta' asLowercase.</lang>

Standard ML

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

Test

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

SQL

Works with: MS SQL version 2005

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

Tcl

<lang tcl>set string alphaBETA

  1. three built-in case conversion commands

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

  1. not built-in

proc swapcase {s} {

   foreach char [split $s ""] {
       if {$char eq [set CHAR [string toupper $char]]} {
           append new [string tolower $char]
       } else {
           append new $CHAR
       }
   }
   return $new

} swapcase $string  ;# ==> ALPHAbeta

  1. better performance, but English alphabet only

proc swapcase_en {s} {

   string map {
       a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z
       A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z
   } $s

}

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

Toka

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

UnixPipes

echo "alphaBETA" |tr '[a-z]' '[A-Z]'
echo "alphaBETA" |tr '[A-Z]' '[a-z]'

Ursala

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

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

  1. show+

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

ALPHABETA
alphabeta

VBScript

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

Vedit macro language

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

Visual Basic .NET

Works with: Visual Basic version 2008

<lang vbnet>' Define 's' Dim s AS String = "alphaBETA"

' Change 's' to Upper Case. s = s.ToUpper()

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

Cookies help us deliver our services. By using our services, you agree to our use of cookies.