Taskintro
Change the case of a string
Also called uppercase, lowercase, to upper case, to lower case, toUpperCase, toLowerCase, upper, lower, capitalize, case conversion.
Change a string to upper case or lower case, and know when the Unicode case change of the library changes the length or depends on the locale.
- Evidence
- Code in 10 languages
Task
Change the case of a string. The function to_upper(s) changes each ASCII letter from a to z to the letter from A to Z, and the function to_lower(s) does the opposite. Each other code point stays the same. For example, to_upper("Hello, World!") is HELLO, WORLD!, and to_upper("café") is CAFé.
This is the ASCII case change. A program uses it for keywords, identifiers, hex digits, protocol names and file extensions, where the result must be the same on each computer. For text that people read, use the Unicode case change of the library, and read the pitfalls. The concept page Case mapping and case folding tells how the Unicode case change works.
Solutions
| Language | Case change of the library | ASCII case change |
|---|---|---|
| Python | s.upper() |
s.translate(table) with the 26 letters |
| JavaScript, TypeScript | s.toUpperCase() |
s.replace(/[a-z]+/g, ...) |
| Java | s.toUpperCase(Locale.ROOT) |
a loop over the char values |
| C# | s.ToUpperInvariant() |
a loop in string.Create |
| Go | strings.ToUpper(s) |
strings.Map with the 26 letters |
| Rust | s.to_uppercase() |
s.to_ascii_uppercase() |
| C | toupper on each byte, in the current locale |
a compare with 'a' and 'z' |
| C++ | std::toupper on each byte |
a compare with 'a' and 'z' |
| Bash | ${s^^} |
tr with LC_ALL=C |
- Python.
str.upperreturns "a copy of the string with all the cased characters [4] converted to uppercase"1. A table fromstr.maketranschanges only the 26 letters. - JavaScript and TypeScript.
toUpperCase"returns this string converted to uppercase"2. The code uses it only on a run of ASCII letters. - Java. The loop changes each
charfromatoz. A UTF-16 code unit of a code point above U+FFFF is never in this range, so the loop is correct for each string. - C#.
ToUpperInvariantreturns "a copy of this String object converted to uppercase using the casing rules of the invariant culture"3. The invariant culture changes the letters of Unicode too, so the code uses a loop. - Go. "ToUpper returns s with all Unicode letters mapped to their upper case"4.
strings.Mapcalls a function for each rune. - Rust. For
to_ascii_uppercase, "ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged"5. - C and C++. The bytes of a UTF-8 sequence are 0x80 or more, so a compare of each byte with
'a'and'z'changes only the ASCII letters. It does not use the locale. - Bash.
trwithLC_ALL=Cchanges the bytes, and it works in each version of Bash.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of to_lower are in cases/lower.jsonl.
empty: the empty string stays empty.digits-punct: digits,-and_do not change.non-ascii,sharp-s,greekandfullwidth:é,ß,σand the fullwidtha(U+FF41) do not change. The Unicode case change of the library changes each of them.dotless-iandlower-dotted-i: the dotlessı(U+0131) and the capitalİ(U+0130) do not change.lower-kelvin: the KELVIN SIGN (U+212A) looks likeK, but it is not an ASCII letter.astral: an emoji between two letters stays the same.combining:cafefollowed by U+0301 COMBINING ACUTE ACCENT changes toCAFEfollowed by U+0301.
Pitfalls
- The length can change. Python uses "section 3.13.2 ‘Default Case Conversion’ of the Unicode Standard"1, and
ßchanges toSS. The lower case ofİis 2 code points. To compare strings with no case, usecasefold, notlower:
s = "straße"
print(s.upper(), len(s), len(s.upper()))
print(len("İ".lower()))
print("Straße".casefold() == "STRASSE".casefold())
STRASSE 6 7
2
True
- JavaScript toLocaleUpperCase uses a locale. It changes the string "according to any locale-specific case mappings"6, and in Turkish the capital of
iisİ(U+0130):
console.log("straße".toUpperCase());
console.log("i".toUpperCase());
console.log("i".toLocaleUpperCase("tr").codePointAt(0).toString(16));
STRASSE
I
130
- Java toLowerCase() uses the default locale. "This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently"7. In the Turkish locale,
TITLEchanges totıtlewith U+0131. UsetoLowerCase(Locale.ROOT). Also, "the resulting String and this String may differ in length"7:
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale tr = Locale.forLanguageTag("tr");
System.out.println("TITLE".toLowerCase(Locale.ROOT));
System.out.println(Integer.toHexString("TITLE".toLowerCase(tr).charAt(1)));
System.out.println("straße".toUpperCase(Locale.ROOT).length());
}
}
title
131
7
- C# ToUpper uses the current culture. For a name of the system, "such as a file name, named pipe, or registry key, use the ToLowerInvariant or ToUpperInvariant method. This produces the same result in every culture and performs more efficiently"8. The output shows that
ToUpperInvariantchangesétoÉ(U+00C9), and that it keeps the length ofstraße:
using System;
using System.Globalization;
var tr = new CultureInfo("tr-TR");
Console.WriteLine("i".ToUpperInvariant());
Console.WriteLine(((int)"i".ToUpper(tr)[0]).ToString("X4"));
Console.WriteLine(((int)"é".ToUpperInvariant()[0]).ToString("X4"));
Console.WriteLine("straße".ToUpperInvariant().Length);
I
0130
00C9
6
- Go has a special case for Turkish.
ToUpperSpecialchanges the letters "using the case mapping specified by c"4. For a compare with no case, useEqualFold, which compares "under simple Unicode case-folding"4:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
fmt.Println(strings.ToUpper("istanbul"))
fmt.Printf("%U\n", []rune(strings.ToUpperSpecial(unicode.TurkishCase, "i")))
fmt.Println(strings.EqualFold("Go", "GO"))
}
ISTANBUL
[U+0130]
true
- Rust to_uppercase returns a new String. "Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place"5.
char::to_uppercasereturns "an iterator that yields the uppercase mapping of this char as one or more chars"9:
fn main() {
let s = "stra\u{df}e";
println!("{}", s.to_uppercase());
println!("{}", s.to_ascii_uppercase().chars().count());
println!("{}", '\u{df}'.to_uppercase().count());
}
STRASSE
6
2
- C toupper takes one byte. In the C locale, "the following lowercase letters abcdefghijklmnopqrstuvwxyz are replaced with respective uppercase letters ABCDEFGHIJKLMNOPQRSTUVWXYZ"10. It cannot change
é, which is 2 bytes in UTF-8. Cast eachchartounsigned charfirst:
#include <ctype.h>
#include <stdio.h>
int main(void) {
char s[] = "caf\xc3\xa9";
for (char *p = s; *p != '\0'; p++) {
*p = (char)toupper((unsigned char)*p);
}
for (char *p = s; *p != '\0'; p++) {
printf(p == s ? "%02x" : " %02x", (unsigned char)*p);
}
printf("\n");
return 0;
}
43 41 46 c3 a9
- C++ std::toupper with a negative char. cppreference says that "the behavior of std::toupper is undefined if the argument's value is neither representable as unsigned char nor equal to EOF"11. With
std::transform, use a lambda that takes anunsigned char:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World";
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
std::cout << s << "\n";
}
HELLO, WORLD
- Bash has case expansions. "This expansion modifies the case of alphabetic characters in parameter"12.
${s^^}changes each letter,${s^}changes the first letter and${s,,}changes each letter to lower case. A script for many shells can usetr:
s='hello, world'
echo "${s^^}"
echo "${s^}"
t='HELLO'
echo "${t,,}"
printf '%s\n' "$s" | LC_ALL=C tr 'a-z' 'A-Z'
HELLO, WORLD
Hello, world
hello
HELLO, WORLD
Related tasks
- Compare strings: compare two strings after a change of case.
- Check whether a string is empty: another check that a program does on text from a user.
- Normalize Unicode text: change the two forms of
éto the same code points before a case change. - Trim white space: remove the white space before a compare with no case.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/change-the-case-of-a-string/.
"""Change the case of the ASCII letters of a string."""
_UPPER = str.maketrans("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
def to_upper(s: str) -> str:
"""Return s with a to z changed to A to Z.
str.upper changes each cased character, and "ß".upper() is "SS", so the
function uses a table of the 26 ASCII letters.
"""
return s.translate(_UPPER)
def to_lower(s: str) -> str:
"""Return s with A to Z changed to a to z."""
return s.translate(_LOWER)
test_case.py 43 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/change-the-case-of-a-string/.
import pytest
from case import to_lower, to_upper
# Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
UPPER = {
"word": ("hello", "HELLO"),
"mixed": ("Hello, World!", "HELLO, WORLD!"),
"already": ("ABC", "ABC"),
"empty": ("", ""),
"digits-punct": ("a1-b2_c3", "A1-B2_C3"),
"non-ascii": ("caf\u00e9", "CAF\u00e9"),
"sharp-s": ("stra\u00dfe", "STRA\u00dfE"),
"dotless-i": ("\u0131 i", "\u0131 I"),
"greek": ("\u03c3", "\u03c3"),
"fullwidth": ("\uff41", "\uff41"),
"astral": ("a\U0001f642b", "A\U0001f642B"),
"combining": ("cafe\u0301", "CAFE\u0301"),
}
LOWER = {
"lower-word": ("HELLO", "hello"),
"lower-mixed": ("Hello, World!", "hello, world!"),
"lower-empty": ("", ""),
"lower-dotted-i": ("\u0130", "\u0130"),
"lower-sigma": ("\u03a3\u0391\u03a3", "\u03a3\u0391\u03a3"),
"lower-kelvin": ("\u212a", "\u212a"),
"lower-astral": ("A\U0001f642B", "a\U0001f642b"),
}
@pytest.mark.parametrize("name", UPPER)
def test_to_upper(name):
s, want = UPPER[name]
assert to_upper(s) == want
@pytest.mark.parametrize("name", LOWER)
def test_to_lower(name):
s, want = LOWER[name]
assert to_lower(s) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
#include "case.hpp"
// std::toupper depends on the locale and is undefined for a negative char, so
// the functions compare each byte with the ASCII letters.
std::string to_upper(std::string_view s) {
std::string out(s);
for (char &c : out) {
if (c >= 'a' && c <= 'z') {
c = static_cast<char>(c - 'a' + 'A');
}
}
return out;
}
std::string to_lower(std::string_view s) {
std::string out(s);
for (char &c : out) {
if (c >= 'A' && c <= 'Z') {
c = static_cast<char>(c - 'A' + 'a');
}
}
return out;
}
case.hpp 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
#ifndef CASE_HPP
#define CASE_HPP
#include <string>
#include <string_view>
// to_upper returns s with a to z changed to A to Z. The other bytes of the
// UTF-8 string do not change.
std::string to_upper(std::string_view s);
// to_lower returns s with A to Z changed to a to z.
std::string to_lower(std::string_view s);
#endif
test_case.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
#include "case.hpp"
#include <iostream>
#include <string>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, const std::string &got, std::string_view want) {
if (got != want) {
std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
failures++;
}
}
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
int main() {
check("word", to_upper("hello"), "HELLO");
check("mixed", to_upper("Hello, World!"), "HELLO, WORLD!");
check("already", to_upper("ABC"), "ABC");
check("empty", to_upper(""), "");
check("digits-punct", to_upper("a1-b2_c3"), "A1-B2_C3");
check("non-ascii", to_upper("caf\xc3\xa9"), "CAF\xc3\xa9");
check("sharp-s", to_upper("stra\xc3\x9f" "e"), "STRA\xc3\x9f" "E");
check("dotless-i", to_upper("\xc4\xb1 i"), "\xc4\xb1 I");
check("greek", to_upper("\xcf\x83"), "\xcf\x83");
check("fullwidth", to_upper("\xef\xbd\x81"), "\xef\xbd\x81");
check("astral", to_upper("a\xf0\x9f\x99\x82" "b"), "A\xf0\x9f\x99\x82" "B");
check("combining", to_upper("cafe\xcc\x81"), "CAFE\xcc\x81");
check("lower-word", to_lower("HELLO"), "hello");
check("lower-mixed", to_lower("Hello, World!"), "hello, world!");
check("lower-empty", to_lower(""), "");
check("lower-dotted-i", to_lower("\xc4\xb0"), "\xc4\xb0");
check("lower-sigma", to_lower("\xce\xa3\xce\x91\xce\xa3"), "\xce\xa3\xce\x91\xce\xa3");
check("lower-kelvin", to_lower("\xe2\x84\xaa"), "\xe2\x84\xaa");
check("lower-astral", to_lower("A\xf0\x9f\x99\x82" "B"), "a\xf0\x9f\x99\x82" "b");
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
/** Changes the case of the ASCII letters of a string. */
public final class Case {
private Case() {}
/**
* Returns s with a to z changed to A to Z. toUpperCase() uses the default
* locale, and toUpperCase(Locale.ROOT) changes the letters of Unicode, so the
* loop changes only the ASCII letters.
*/
public static String toUpper(String s) {
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
if (cs[i] >= 'a' && cs[i] <= 'z') {
cs[i] = (char) (cs[i] - 'a' + 'A');
}
}
return new String(cs);
}
/** Returns s with A to Z changed to a to z. */
public static String toLower(String s) {
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
if (cs[i] >= 'A' && cs[i] <= 'Z') {
cs[i] = (char) (cs[i] - 'A' + 'a');
}
}
return new String(cs);
}
}
CaseTest.java 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class CaseTest {
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
static Stream<Arguments> upper() {
return Stream.of(
Arguments.of("word", "hello", "HELLO"),
Arguments.of("mixed", "Hello, World!", "HELLO, WORLD!"),
Arguments.of("already", "ABC", "ABC"),
Arguments.of("empty", "", ""),
Arguments.of("digits-punct", "a1-b2_c3", "A1-B2_C3"),
Arguments.of("non-ascii", "caf\u00e9", "CAF\u00e9"),
Arguments.of("sharp-s", "stra\u00dfe", "STRA\u00dfE"),
Arguments.of("dotless-i", "\u0131 i", "\u0131 I"),
Arguments.of("greek", "\u03c3", "\u03c3"),
Arguments.of("fullwidth", "\uff41", "\uff41"),
Arguments.of("astral", "a\ud83d\ude42b", "A\ud83d\ude42B"),
Arguments.of("combining", "cafe\u0301", "CAFE\u0301"));
}
static Stream<Arguments> lower() {
return Stream.of(
Arguments.of("lower-word", "HELLO", "hello"),
Arguments.of("lower-mixed", "Hello, World!", "hello, world!"),
Arguments.of("lower-empty", "", ""),
Arguments.of("lower-dotted-i", "\u0130", "\u0130"),
Arguments.of("lower-sigma", "\u03a3\u0391\u03a3", "\u03a3\u0391\u03a3"),
Arguments.of("lower-kelvin", "\u212a", "\u212a"),
Arguments.of("lower-astral", "A\ud83d\ude42B", "a\ud83d\ude42b"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("upper")
void toUpper(String name, String s, String want) {
assertEquals(want, Case.toUpper(s));
}
@ParameterizedTest(name = "{0}")
@MethodSource("lower")
void toLower(String name, String s, String want) {
assertEquals(want, Case.toLower(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
#include "case.h"
#include <stdlib.h>
#include <string.h>
// toupper depends on the locale, and its argument must be an unsigned char
// value, so the function compares each byte with the ASCII letters. The
// bytes of a UTF-8 sequence are 0x80 or more, so they do not change.
static char *map(const char *s, char lo, char hi, int delta) {
size_t n = strlen(s);
char *out = malloc(n + 1);
if (out == NULL) {
return NULL;
}
for (size_t i = 0; i <= n; i++) {
char c = s[i];
out[i] = (c >= lo && c <= hi) ? (char)(c + delta) : c;
}
return out;
}
char *to_upper(const char *s) { return map(s, 'a', 'z', 'A' - 'a'); }
char *to_lower(const char *s) { return map(s, 'A', 'Z', 'a' - 'A'); }
case.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
#ifndef CASE_H
#define CASE_H
// to_upper returns a new string with a to z of the UTF-8 string s changed to
// A to Z, or NULL if there is no memory. The caller frees the result.
char *to_upper(const char *s);
// to_lower returns a new string with A to Z changed to a to z, or NULL if
// there is no memory. The caller frees the result.
char *to_lower(const char *s);
#endif
test_case.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
#include "case.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
// check frees got, which is a new string from to_upper or to_lower.
static void check(const char *name, char *got, const char *want) {
if (got == NULL || strcmp(got, want) != 0) {
fprintf(stderr, "case %s: got %s, want %s\n", name, got ? got : "NULL", want);
failures++;
}
free(got);
}
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
int main(void) {
check("word", to_upper("hello"), "HELLO");
check("mixed", to_upper("Hello, World!"), "HELLO, WORLD!");
check("already", to_upper("ABC"), "ABC");
check("empty", to_upper(""), "");
check("digits-punct", to_upper("a1-b2_c3"), "A1-B2_C3");
check("non-ascii", to_upper("caf\xc3\xa9"), "CAF\xc3\xa9");
check("sharp-s", to_upper("stra\xc3\x9f" "e"), "STRA\xc3\x9f" "E");
check("dotless-i", to_upper("\xc4\xb1 i"), "\xc4\xb1 I");
check("greek", to_upper("\xcf\x83"), "\xcf\x83");
check("fullwidth", to_upper("\xef\xbd\x81"), "\xef\xbd\x81");
check("astral", to_upper("a\xf0\x9f\x99\x82" "b"), "A\xf0\x9f\x99\x82" "B");
check("combining", to_upper("cafe\xcc\x81"), "CAFE\xcc\x81");
check("lower-word", to_lower("HELLO"), "hello");
check("lower-mixed", to_lower("Hello, World!"), "hello, world!");
check("lower-empty", to_lower(""), "");
check("lower-dotted-i", to_lower("\xc4\xb0"), "\xc4\xb0");
check("lower-sigma", to_lower("\xce\xa3\xce\x91\xce\xa3"), "\xce\xa3\xce\x91\xce\xa3");
check("lower-kelvin", to_lower("\xe2\x84\xaa"), "\xe2\x84\xaa");
check("lower-astral", to_lower("A\xf0\x9f\x99\x82" "B"), "a\xf0\x9f\x99\x82" "b");
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
/// <summary>Changes the case of the ASCII letters of a string.</summary>
public static class AsciiCase
{
/// <summary>
/// Returns s with a to z changed to A to Z. ToUpperInvariant changes the
/// letters of Unicode too, so the function changes only the ASCII letters.
/// </summary>
public static string ToUpper(string s) =>
string.Create(s.Length, s, static (span, src) =>
{
for (int i = 0; i < src.Length; i++)
{
char c = src[i];
span[i] = c >= 'a' && c <= 'z' ? (char)(c - 'a' + 'A') : c;
}
});
/// <summary>Returns s with A to Z changed to a to z.</summary>
public static string ToLower(string s) =>
string.Create(s.Length, s, static (span, src) =>
{
for (int i = 0; i < src.Length; i++)
{
char c = src[i];
span[i] = c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
}
});
}
CaseTests.cs 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
using Xunit;
public sealed class CaseTests
{
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
public static TheoryData<string, string, string> Upper => new()
{
{ "word", "hello", "HELLO" },
{ "mixed", "Hello, World!", "HELLO, WORLD!" },
{ "already", "ABC", "ABC" },
{ "empty", "", "" },
{ "digits-punct", "a1-b2_c3", "A1-B2_C3" },
{ "non-ascii", "caf\u00e9", "CAF\u00e9" },
{ "sharp-s", "stra\u00dfe", "STRA\u00dfE" },
{ "dotless-i", "\u0131 i", "\u0131 I" },
{ "greek", "\u03c3", "\u03c3" },
{ "fullwidth", "\uff41", "\uff41" },
{ "astral", "a\U0001f642b", "A\U0001f642B" },
{ "combining", "cafe\u0301", "CAFE\u0301" },
};
public static TheoryData<string, string, string> Lower => new()
{
{ "lower-word", "HELLO", "hello" },
{ "lower-mixed", "Hello, World!", "hello, world!" },
{ "lower-empty", "", "" },
{ "lower-dotted-i", "\u0130", "\u0130" },
{ "lower-sigma", "\u03a3\u0391\u03a3", "\u03a3\u0391\u03a3" },
{ "lower-kelvin", "\u212a", "\u212a" },
{ "lower-astral", "A\U0001f642B", "a\U0001f642b" },
};
[Theory]
[MemberData(nameof(Upper))]
public void ToUpper(string name, string s, string want)
{
Assert.NotNull(name);
Assert.Equal(want, AsciiCase.ToUpper(s));
}
[Theory]
[MemberData(nameof(Lower))]
public void ToLower(string name, string s, string want)
{
Assert.NotNull(name);
Assert.Equal(want, AsciiCase.ToLower(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
// toUpper returns s with a to z changed to A to Z. toUpperCase changes each
// letter of Unicode, and "ß".toUpperCase() is "SS", so the function
// changes only the ASCII letters.
export function toUpper(s) {
return s.replace(/[a-z]+/g, (m) => m.toUpperCase());
}
// toLower returns s with A to Z changed to a to z.
export function toLower(s) {
return s.replace(/[A-Z]+/g, (m) => m.toLowerCase());
}
case.test.js 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toLower, toUpper } from "./case.js";
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
const upper = [
["word", "hello", "HELLO"],
["mixed", "Hello, World!", "HELLO, WORLD!"],
["already", "ABC", "ABC"],
["empty", "", ""],
["digits-punct", "a1-b2_c3", "A1-B2_C3"],
["non-ascii", "caf\u00e9", "CAF\u00e9"],
["sharp-s", "stra\u00dfe", "STRA\u00dfE"],
["dotless-i", "\u0131 i", "\u0131 I"],
["greek", "\u03c3", "\u03c3"],
["fullwidth", "\uff41", "\uff41"],
["astral", "a\u{1f642}b", "A\u{1f642}B"],
["combining", "cafe\u0301", "CAFE\u0301"],
];
const lower = [
["lower-word", "HELLO", "hello"],
["lower-mixed", "Hello, World!", "hello, world!"],
["lower-empty", "", ""],
["lower-dotted-i", "\u0130", "\u0130"],
["lower-sigma", "\u03a3\u0391\u03a3", "\u03a3\u0391\u03a3"],
["lower-kelvin", "\u212a", "\u212a"],
["lower-astral", "A\u{1f642}B", "a\u{1f642}b"],
];
for (const [name, s, want] of upper) {
test(name, () => {
assert.equal(toUpper(s), want);
});
}
for (const [name, s, want] of lower) {
test(name, () => {
assert.equal(toLower(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
// toUpper returns s with a to z changed to A to Z. toUpperCase changes each
// letter of Unicode, and "ß".toUpperCase() is "SS", so the function
// changes only the ASCII letters.
export function toUpper(s: string): string {
return s.replace(/[a-z]+/g, (m: string) => m.toUpperCase());
}
// toLower returns s with A to Z changed to a to z.
export function toLower(s: string): string {
return s.replace(/[A-Z]+/g, (m: string) => m.toLowerCase());
}
case.test.ts 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toLower, toUpper } from "./case.ts";
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
const upper = [
["word", "hello", "HELLO"],
["mixed", "Hello, World!", "HELLO, WORLD!"],
["already", "ABC", "ABC"],
["empty", "", ""],
["digits-punct", "a1-b2_c3", "A1-B2_C3"],
["non-ascii", "caf\u00e9", "CAF\u00e9"],
["sharp-s", "stra\u00dfe", "STRA\u00dfE"],
["dotless-i", "\u0131 i", "\u0131 I"],
["greek", "\u03c3", "\u03c3"],
["fullwidth", "\uff41", "\uff41"],
["astral", "a\u{1f642}b", "A\u{1f642}B"],
["combining", "cafe\u0301", "CAFE\u0301"],
];
const lower = [
["lower-word", "HELLO", "hello"],
["lower-mixed", "Hello, World!", "hello, world!"],
["lower-empty", "", ""],
["lower-dotted-i", "\u0130", "\u0130"],
["lower-sigma", "\u03a3\u0391\u03a3", "\u03a3\u0391\u03a3"],
["lower-kelvin", "\u212a", "\u212a"],
["lower-astral", "A\u{1f642}B", "a\u{1f642}b"],
];
for (const [name, s, want] of upper) {
test(name, () => {
assert.equal(toUpper(s), want);
});
}
for (const [name, s, want] of lower) {
test(name, () => {
assert.equal(toLower(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
// Package asciicase changes the case of the ASCII letters of a string.
package asciicase
import "strings"
// ToUpper returns s with a to z changed to A to Z. strings.ToUpper changes
// each letter of Unicode, so the function maps only the ASCII letters.
func ToUpper(s string) string {
return strings.Map(func(r rune) rune {
if 'a' <= r && r <= 'z' {
return r - 'a' + 'A'
}
return r
}, s)
}
// ToLower returns s with A to Z changed to a to z.
func ToLower(s string) string {
return strings.Map(func(r rune) rune {
if 'A' <= r && r <= 'Z' {
return r - 'A' + 'a'
}
return r
}, s)
}
case_test.go 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
package asciicase
import "testing"
type caseCase struct {
name, s, want string
}
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
var upper = []caseCase{
{"word", "hello", "HELLO"},
{"mixed", "Hello, World!", "HELLO, WORLD!"},
{"already", "ABC", "ABC"},
{"empty", "", ""},
{"digits-punct", "a1-b2_c3", "A1-B2_C3"},
{"non-ascii", "caf\u00e9", "CAF\u00e9"},
{"sharp-s", "stra\u00dfe", "STRA\u00dfE"},
{"dotless-i", "\u0131 i", "\u0131 I"},
{"greek", "\u03c3", "\u03c3"},
{"fullwidth", "\uff41", "\uff41"},
{"astral", "a\U0001f642b", "A\U0001f642B"},
{"combining", "cafe\u0301", "CAFE\u0301"},
}
var lower = []caseCase{
{"lower-word", "HELLO", "hello"},
{"lower-mixed", "Hello, World!", "hello, world!"},
{"lower-empty", "", ""},
{"lower-dotted-i", "\u0130", "\u0130"},
{"lower-sigma", "\u03a3\u0391\u03a3", "\u03a3\u0391\u03a3"},
{"lower-kelvin", "\u212a", "\u212a"},
{"lower-astral", "A\U0001f642B", "a\U0001f642b"},
}
func TestToUpper(t *testing.T) {
for _, c := range upper {
if got := ToUpper(c.s); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestToLower(t *testing.T) {
for _, c := range lower {
if got := ToLower(c.s); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
/// Returns s with a to z changed to A to Z. str::to_uppercase changes each
/// letter of Unicode, and to_ascii_uppercase changes only the ASCII letters.
pub fn to_upper(s: &str) -> String {
s.to_ascii_uppercase()
}
/// Returns s with A to Z changed to a to z.
pub fn to_lower(s: &str) -> String {
s.to_ascii_lowercase()
}
tests/case_test.rs 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/change-the-case-of-a-string/.
use algo_change_the_case_of_a_string::{to_lower, to_upper};
// Only the ASCII letters change. U+0131 is the dotless i, U+0130 is the capital I with a dot, U+212A is the KELVIN SIGN, and U+FF41 is the fullwidth a.
#[test]
fn upper() {
let cases = [
("word", "hello", "HELLO"),
("mixed", "Hello, World!", "HELLO, WORLD!"),
("already", "ABC", "ABC"),
("empty", "", ""),
("digits-punct", "a1-b2_c3", "A1-B2_C3"),
("non-ascii", "caf\u{e9}", "CAF\u{e9}"),
("sharp-s", "stra\u{df}e", "STRA\u{df}E"),
("dotless-i", "\u{131} i", "\u{131} I"),
("greek", "\u{3c3}", "\u{3c3}"),
("fullwidth", "\u{ff41}", "\u{ff41}"),
("astral", "a\u{1f642}b", "A\u{1f642}B"),
("combining", "cafe\u{301}", "CAFE\u{301}"),
];
for (name, s, want) in cases {
assert_eq!(to_upper(s), want, "{name}");
}
}
#[test]
fn lower() {
let cases = [
("lower-word", "HELLO", "hello"),
("lower-mixed", "Hello, World!", "hello, world!"),
("lower-empty", "", ""),
("lower-dotted-i", "\u{130}", "\u{130}"),
("lower-sigma", "\u{3a3}\u{391}\u{3a3}", "\u{3a3}\u{391}\u{3a3}"),
("lower-kelvin", "\u{212a}", "\u{212a}"),
("lower-astral", "A\u{1f642}B", "a\u{1f642}b"),
];
for (name, s, want) in cases {
assert_eq!(to_lower(s), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/change-the-case-of-a-string/.
# to_upper S: prints S with a to z changed to A to Z. The function uses tr
# with LC_ALL=C and the 26 letters, so it changes only the ASCII bytes, and it
# runs in each version of Bash.
to_upper() {
printf '%s' "$1" | LC_ALL=C tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
}
# to_lower S: prints S with A to Z changed to a to z.
to_lower() {
printf '%s' "$1" | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'
}
test_case.bats 35 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/change-the-case-of-a-string/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/case.sh"
}
check() { # check FUNCTION S WANT
run "$1" "$2"
[ "$status" -eq 0 ]
[ "$output" = "$3" ]
}
# Only the ASCII letters change, so each byte of 0x80 or more stays as it is.
@test "word" { check to_upper 'hello' 'HELLO'; }
@test "mixed" { check to_upper 'Hello, World!' 'HELLO, WORLD!'; }
@test "already" { check to_upper 'ABC' 'ABC'; }
@test "empty" { check to_upper '' ''; }
@test "digits-punct" { check to_upper 'a1-b2_c3' 'A1-B2_C3'; }
@test "non-ascii" { check to_upper $'caf\xc3\xa9' $'CAF\xc3\xa9'; }
@test "sharp-s" { check to_upper $'stra\xc3\x9fe' $'STRA\xc3\x9fE'; }
@test "dotless-i" { check to_upper $'\xc4\xb1 i' $'\xc4\xb1 I'; }
@test "greek" { check to_upper $'\xcf\x83' $'\xcf\x83'; }
@test "fullwidth" { check to_upper $'\xef\xbd\x81' $'\xef\xbd\x81'; }
@test "astral" { check to_upper $'a\xf0\x9f\x99\x82b' $'A\xf0\x9f\x99\x82B'; }
@test "combining" { check to_upper $'cafe\xcc\x81' $'CAFE\xcc\x81'; }
@test "lower-word" { check to_lower 'HELLO' 'hello'; }
@test "lower-mixed" { check to_lower 'Hello, World!' 'hello, world!'; }
@test "lower-empty" { check to_lower '' ''; }
@test "lower-dotted-i" { check to_lower $'\xc4\xb0' $'\xc4\xb0'; }
@test "lower-sigma" { check to_lower $'\xce\xa3\xce\x91\xce\xa3' $'\xce\xa3\xce\x91\xce\xa3'; }
@test "lower-kelvin" { check to_lower $'\xe2\x84\xaa' $'\xe2\x84\xaa'; }
@test "lower-astral" { check to_lower $'A\xf0\x9f\x99\x82B' $'a\xf0\x9f\x99\x82b'; }
References
- The Python Standard Library, Built-in Types, str.upper, str.casefold
- MDN Web Docs, String.prototype.toUpperCase(), Description
- .NET API reference, String.ToUpperInvariant method, Summary
- Go standard library, package strings, ToUpper, ToUpperSpecial, EqualFold
- Rust standard library, primitive type str, to_uppercase, to_ascii_uppercase
- MDN Web Docs, String.prototype.toLocaleUpperCase(), Description
- Java SE 25 API, Class String, toLowerCase(), toUpperCase(Locale)
- .NET API reference, String.ToUpper method, Remarks
- Rust standard library, primitive type char, to_uppercase
- cppreference.com, toupper (C), Description
- cppreference.com, std::toupper, Notes
- Bash Reference Manual, 3.5.3 Shell Parameter Expansion
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag G0M5JN Edit this page History Report an error Markdown