Taskintro
Find the length of a string
Also called string length, count the characters of a string, len of a string, size of a string, byte length of a string.
Find the length of a string in UTF-8 bytes, in UTF-16 code units and in code points, and know which of them len, length, size and count give in each language.
- Evidence
- Code in 10 languages
Task
Find the length of a string. A string has more than one length, so the function lengths(s) returns three numbers: the number of bytes in its UTF-8 form, the number of UTF-16 code units, and the number of code points. The built-in length of each language is one of these three. It is not always the number of characters that a reader sees.
UTF-8 uses 1 to 4 bytes for each code point, because characters "are encoded using sequences of 1 to 4 octets"1. UTF-16 uses one 16-bit code unit for a code point up to U+FFFF, and a pair of code units, a high surrogate and a low surrogate, for a code point above U+FFFF2. So "🙂" (U+1F642) has a length of 4 bytes, 2 code units and 1 code point.
The number of graphemes, the characters that a reader sees, is a fourth length. It needs the segmentation rules of Unicode, so it is a separate task, count the graphemes of a string. See grapheme cluster.
Solutions
The built-in length of a string counts the units that the language stores:
| Language | Built-in length | It counts |
|---|---|---|
| Python | len(s) |
code points |
| JavaScript, TypeScript | s.length |
UTF-16 code units |
| Java | s.length() |
UTF-16 code units |
| C# | s.Length |
UTF-16 code units |
| Go | len(s) |
bytes |
| Rust | s.len() |
bytes |
| C | strlen(s) |
bytes before the first null byte |
| C++ | s.size(), s.length() |
char elements, that is, bytes |
| Bash | ${#s} |
characters of the current locale |
- Python. A
stris one of the "immutable sequences of Unicode code points"3, andlenreturns "the number of items"4, solen(s)counts code points. The code encodes the string to count bytes and UTF-16 units. The codecutf-16-lewrites no byte order mark, so the number of bytes divided by 2 is the number of code units. - JavaScript and TypeScript.
lengthgives "the length of the string in UTF-16 code units"5. The string iterator yields code points, so[...s].lengthcounts code points.TextEncoder.encodereturns "A Uint8Array object containing the UTF-8 encoding of the input string"6, and its length is the number of bytes. - Java. For
length(), "The length is equal to the number of Unicode code units in the string"7.codePointCount(0, s.length())counts code points, andgetBytes(StandardCharsets.UTF_8).lengthcounts bytes. - C#. "The Length property returns the number of Char objects in this instance, not the number of Unicode characters"8. A
Charis one UTF-16 code unit.Encoding.UTF8.GetByteCountcalculates "the number of bytes produced by encoding a set of characters"9 and makes no array.EnumerateRunesreturns "an enumeration of Rune from this string"10, and aRuneis one code point. - Go. "A string value is a (possibly empty) sequence of bytes. The number of bytes is called the length of the string"11.
utf8.RuneCountInStringcounts code points12.utf16.RuneLen"returns the number of 16-bit words in the UTF-16 encoding of the rune"13, so the code adds it up over the runes of the string. - Rust. For
str::len, "This length is in bytes, not chars or graphemes"14.s.chars().count()counts code points, ands.encode_utf16().count()counts UTF-16 units. Both walk the whole string. - C. A C string has no stored length.
strlencounts the bytes "up to and not including the first null character"15. The code takes the lengthnas an argument, so the text can hold a null byte. It counts the first bytes of the code points, which are all the bytes that do not have the form10xxxxxx. Each first byte fromF0starts a code point that needs two UTF-16 units. - C++.
size()returns "the number of CharT elements in the string"16, and forstd::stringandstd::string_viewaCharTis a byte. The code counts code points as the C code does, withstd::ranges::count_if. - Bash.
${#s}"Substitutes the length in characters of the value of parameter"17. The locale categoryLC_CTYPE"determines the interpretation of characters"17, so the function counts in the localeC, where each byte is a character, and in the localeC.UTF-8, where each code point is a character. It counts the bytesF0toF4to find the code points that need two UTF-16 units.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: all three lengths are 0.two-byte,three-byteandeuro-sign:ïis 2 bytes and€is 3 bytes in UTF-8, but each is one UTF-16 unit and one code point. A byte length is larger than the code point length for all text that is not ASCII.astralandmixed:🙂is 4 bytes, 2 UTF-16 units and 1 code point. This is the case where JavaScript, Java and C# give a different number from Python.combining-markandprecomposed:écan be one code point, U+00E9, or two,eand U+0301 COMBINING ACUTE ACCENT. A reader sees one character in each case, but every length in this task gives a different number for the two forms. Normalize the text first if the two forms must have the same length.flag: the flag🇫🇷is two regional indicator code points, so its lengths are 8, 4 and 2.zwj-family:👨👩👧is three emoji joined by two U+200D ZERO WIDTH JOINER code points. It is 18 bytes, 8 UTF-16 units and 5 code points, and one grapheme.nul: a null character in the middle. Every language except C and Bash counts it.strlenstops at it, and a Bash variable cannot hold it, so the Bash solution has nonulcase.
Pitfalls
- Python
lencounts code points, not what a reader sees. A letter with a combining mark is two code points. After normalization to NFC, the example has one code point foré:
import unicodedata
word = "cafe\u0301"
print(len(word), len(word.encode("utf-8")))
print(len(unicodedata.normalize("NFC", word)))
print(len("🙂"), len("🙂".encode("utf-8")))
5 6
4
1 4
- JavaScript
lengthcounts UTF-16 code units. A code point above U+FFFF is two units, andcharCodeAt(0)gives only its high surrogate.[...s].lengthcounts code points, andIntl.Segmenter, which gets "meaningful items (graphemes, words or sentences) from a string"18, counts graphemes:
const smile = "🙂";
console.log(smile.length, [...smile].length);
console.log(smile.charCodeAt(0).toString(16), smile.codePointAt(0).toString(16));
const family = "👨👩👧";
const graphemes = [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(family)];
console.log(family.length, [...family].length, graphemes.length);
2 1
d83d 1f642
8 5 1
- Java
length()andcharAtsee code units. Thecharat index 1 of"a🙂b"is half of the emoji:
public class Main {
public static void main(String[] args) {
String s = "a🙂b";
System.out.println(s.length() + " " + s.codePointCount(0, s.length()));
System.out.println(Integer.toHexString(s.charAt(1)) + " " + Character.isHighSurrogate(s.charAt(1)));
}
}
4 3
d83d true
- C#
LengthcountsCharvalues.EnumerateRunescounts code points. The documentation says to "Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char"8, andStringInfo.LengthInTextElementscounts the text elements:
using System.Globalization;
using System.Text;
var s = "e\u0301🙂";
Console.WriteLine($"{s.Length} {s.EnumerateRunes().Count()} {new StringInfo(s).LengthInTextElements}");
Console.WriteLine(Encoding.UTF8.GetByteCount(s));
4 3 2
7
- Go
lenand a loop over the index see bytes. Afor rangeloop over the string itself yields runes and the byte index of each:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "日本語"
fmt.Println(len(s), utf8.RuneCountInString(s))
for i := range len(s) {
fmt.Printf("%x ", s[i])
}
fmt.Println()
for i, r := range s {
fmt.Print(i, ":", string(r), " ")
}
fmt.Println()
}
9 3
e6 97 a5 e6 9c ac e8 aa 9e
0:日 3:本 6:語
- A byte length in Rust is not a safe place to cut.
s.len()is in bytes, and a slice must start and end on a character boundary.getis "the non-panicking alternative to indexing the str"14, so it returnsNonefor a range that ends inside a character, where&s[0..3]panics:
fn main() {
let s = "naïve";
println!("{} {}", s.len(), s.chars().count());
println!("{} {}", s.is_char_boundary(2), s.is_char_boundary(3));
println!("{:?}", s.get(0..3));
println!("{:?}", s.get(0..4));
}
6 5
true false
None
Some("naï")
- C
strlenstops at the first null byte, andsizeofcounts the terminator.sizeofof a character array gives the size of the array, which includes the null character at the end of the literal. Neither is the number of characters of UTF-8 text:
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "a\0b";
printf("%zu %zu\n", strlen(text), sizeof text);
const char *word = "naïve";
printf("%zu\n", strlen(word));
}
1 4
6
- Bash
${#s}depends on the locale. In theClocale,${#s}ofnaïveis 6. In a UTF-8 locale, it is 5. A script that counts characters must setLC_ALLorLC_CTYPE. - A length is not a display width. The width of text on a terminal or a page is a different number, and none of the lengths in this task gives it.
Related tasks
- Reverse a string: a reverse by code units breaks the same characters that a count by code units counts twice.
- Split a string: the byte search of the split works because UTF-8 has a fixed form for each first byte.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-length-of-a-string/.
def lengths(s: str) -> list[int]:
"""Return the length of s in UTF-8 bytes, in UTF-16 code units and in code points."""
utf8 = len(s.encode("utf-8"))
# Each UTF-16 code unit is 2 bytes. The -le codec writes no byte order mark.
utf16 = len(s.encode("utf-16-le")) // 2
# A str is a sequence of code points, so len counts code points.
return [utf8, utf16, len(s)]
test_string_length.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-length-of-a-string/.
import pytest
from string_length import lengths
CASES = {
"ascii": ("hello", [5, 5, 5]),
"words": ("Hello, world", [12, 12, 12]),
"two-byte": ("naïve", [6, 5, 5]),
"three-byte": ("日本語", [9, 3, 3]),
"cyrillic": ("Привет", [12, 6, 6]),
"empty": ("", [0, 0, 0]),
"single": ("a", [1, 1, 1]),
"euro-sign": ("€", [3, 1, 1]),
"astral": ("🙂", [4, 2, 1]),
"mixed": ("a🙂b", [6, 4, 3]),
"combining-mark": ("e\u0301", [3, 2, 2]),
"precomposed": ("é", [2, 1, 1]),
"flag": ("🇫🇷", [8, 4, 2]),
"zwj-family": ("👨\u200d👩\u200d👧", [18, 8, 5]),
"nul": ("a\u0000b", [3, 3, 3]),
}
@pytest.mark.parametrize("name", CASES)
def test_lengths(name):
s, want = CASES[name]
assert lengths(s) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
#include "string_length.hpp"
#include <algorithm>
std::array<std::size_t, 3> lengths(std::string_view s) {
// Each code point has one first byte. A continuation byte is 10xxxxxx.
auto code_points = static_cast<std::size_t>(
std::ranges::count_if(s, [](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; }));
// A first byte 11110xxx starts a code point above U+FFFF, and UTF-16 needs
// two code units for it.
auto four_byte =
static_cast<std::size_t>(std::ranges::count_if(s, [](char c) { return static_cast<unsigned char>(c) >= 0xF0; }));
return {s.size(), code_points + four_byte, code_points};
}
string_length.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
#pragma once
#include <array>
#include <cstddef>
#include <string_view>
// Returns three lengths of the valid UTF-8 string s: the number of bytes, the
// number of UTF-16 code units and the number of code points.
std::array<std::size_t, 3> lengths(std::string_view s);
test_string_length.cpp 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
#include <array>
#include <cstddef>
#include <cstdio>
#include <string_view>
#include "string_length.hpp"
int main() {
using namespace std::string_view_literals;
struct Case {
std::string_view name, s;
std::array<std::size_t, 3> want;
};
// The sv literals keep the null character of the nul case.
const Case cases[] = {
{"ascii", "hello"sv, {5, 5, 5}},
{"words", "Hello, world"sv, {12, 12, 12}},
{"two-byte", "naïve"sv, {6, 5, 5}},
{"three-byte", "日本語"sv, {9, 3, 3}},
{"cyrillic", "Привет"sv, {12, 6, 6}},
{"empty", ""sv, {0, 0, 0}},
{"single", "a"sv, {1, 1, 1}},
{"euro-sign", "€"sv, {3, 1, 1}},
{"astral", "🙂"sv, {4, 2, 1}},
{"mixed", "a🙂b"sv, {6, 4, 3}},
{"combining-mark", "e\xcc\x81"sv, {3, 2, 2}},
{"precomposed", "\xc3\xa9"sv, {2, 1, 1}},
{"flag", "🇫🇷"sv, {8, 4, 2}},
{"zwj-family", "👨\xe2\x80\x8d👩\xe2\x80\x8d👧"sv, {18, 8, 5}},
{"nul", "a\0b"sv, {3, 3, 3}},
};
int failures = 0;
for (const auto& c : cases) {
if (lengths(c.s) != c.want) {
std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(c.name.size()), c.name.data());
++failures;
}
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
import java.nio.charset.StandardCharsets;
/** Finds the lengths of a string in UTF-8 bytes, in UTF-16 code units and in code points. */
public final class StringLength {
private StringLength() {}
/** Returns the length of s in UTF-8 bytes, in UTF-16 code units and in code points. */
public static int[] lengths(String s) {
// A String is a sequence of UTF-16 code units, and length() counts them.
return new int[] {
s.getBytes(StandardCharsets.UTF_8).length, s.length(), s.codePointCount(0, s.length())
};
}
}
StringLengthTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 StringLengthTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("ascii", "hello", new int[] {5, 5, 5}),
Arguments.of("words", "Hello, world", new int[] {12, 12, 12}),
Arguments.of("two-byte", "naïve", new int[] {6, 5, 5}),
Arguments.of("three-byte", "日本語", new int[] {9, 3, 3}),
Arguments.of("cyrillic", "Привет", new int[] {12, 6, 6}),
Arguments.of("empty", "", new int[] {0, 0, 0}),
Arguments.of("single", "a", new int[] {1, 1, 1}),
Arguments.of("euro-sign", "€", new int[] {3, 1, 1}),
Arguments.of("astral", "🙂", new int[] {4, 2, 1}),
Arguments.of("mixed", "a🙂b", new int[] {6, 4, 3}),
Arguments.of("combining-mark", "e\u0301", new int[] {3, 2, 2}),
Arguments.of("precomposed", "é", new int[] {2, 1, 1}),
Arguments.of("flag", "🇫🇷", new int[] {8, 4, 2}),
Arguments.of("zwj-family", "👨\u200d👩\u200d👧", new int[] {18, 8, 5}),
Arguments.of("nul", "a\u0000b", new int[] {3, 3, 3}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void lengths(String name, String s, int[] want) {
assertArrayEquals(want, StringLength.lengths(s), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
#include "string_length.h"
void lengths(const char *s, size_t n, size_t out[3]) {
size_t code_points = 0, four_byte = 0;
for (size_t i = 0; i < n; i++) {
unsigned char b = (unsigned char)s[i];
// Each code point has one first byte. A continuation byte is 10xxxxxx.
if ((b & 0xC0) != 0x80) {
code_points++;
}
// A first byte 11110xxx starts a code point above U+FFFF, and UTF-16
// needs two code units for it.
if (b >= 0xF0) {
four_byte++;
}
}
out[0] = n;
out[1] = code_points + four_byte;
out[2] = code_points;
}
string_length.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
#ifndef STRING_LENGTH_H
#define STRING_LENGTH_H
#include <stddef.h>
// lengths writes three lengths of the valid UTF-8 bytes s[0..n) to out: the
// number of bytes, the number of UTF-16 code units and the number of code
// points. The bytes can include a null character.
void lengths(const char *s, size_t n, size_t out[3]);
#endif
test_string_length.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
#include "string_length.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const char *s, size_t n, size_t units, size_t code_points) {
size_t out[3];
lengths(s, n, out);
if (out[0] != n || out[1] != units || out[2] != code_points) {
fprintf(stderr, "case %s: got %zu %zu %zu\n", name, out[0], out[1], out[2]);
failures++;
}
}
// The array of a string literal also holds the terminating null character, so
// the number of bytes of the text is sizeof minus 1. strlen stops at the first
// null character, so it is wrong for the nul case.
#define CHECK(name, lit, units, code_points) check(name, lit, sizeof(lit) - 1, units, code_points)
int main(void) {
CHECK("ascii", "hello", 5, 5);
CHECK("words", "Hello, world", 12, 12);
CHECK("two-byte", "naïve", 5, 5);
CHECK("three-byte", "日本語", 3, 3);
CHECK("cyrillic", "Привет", 6, 6);
CHECK("empty", "", 0, 0);
CHECK("single", "a", 1, 1);
CHECK("euro-sign", "€", 1, 1);
CHECK("astral", "🙂", 2, 1);
CHECK("mixed", "a🙂b", 4, 3);
// U+0301 COMBINING ACUTE ACCENT is CC 81 in UTF-8.
CHECK("combining-mark", "e\xcc\x81", 2, 2);
CHECK("precomposed", "\xc3\xa9", 1, 1);
CHECK("flag", "🇫🇷", 4, 2);
// U+200D ZERO WIDTH JOINER is E2 80 8D in UTF-8.
CHECK("zwj-family", "👨\xe2\x80\x8d👩\xe2\x80\x8d👧", 8, 5);
CHECK("nul", "a\0b", 3, 3);
if (failures != 0) {
return 1;
}
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
using System.Text;
/// <summary>Finds the lengths of a string in UTF-8 bytes, in UTF-16 code units and in code points.</summary>
public static class StringLength
{
/// <summary>Returns the length of s in UTF-8 bytes, in UTF-16 code units and in code points.</summary>
public static int[] Lengths(string s)
{
// A string is a sequence of UTF-16 char values, and Length counts them.
// A Rune is one Unicode scalar value, that is, one code point.
var codePoints = 0;
foreach (var _ in s.EnumerateRunes())
{
codePoints++;
}
return [Encoding.UTF8.GetByteCount(s), s.Length, codePoints];
}
}
StringLengthTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
using Xunit;
public sealed class StringLengthTests
{
public static TheoryData<string, string, int[]> Cases => new()
{
{ "ascii", "hello", [5, 5, 5] },
{ "words", "Hello, world", [12, 12, 12] },
{ "two-byte", "naïve", [6, 5, 5] },
{ "three-byte", "日本語", [9, 3, 3] },
{ "cyrillic", "Привет", [12, 6, 6] },
{ "empty", "", [0, 0, 0] },
{ "single", "a", [1, 1, 1] },
{ "euro-sign", "€", [3, 1, 1] },
{ "astral", "🙂", [4, 2, 1] },
{ "mixed", "a🙂b", [6, 4, 3] },
{ "combining-mark", "e\u0301", [3, 2, 2] },
{ "precomposed", "é", [2, 1, 1] },
{ "flag", "🇫🇷", [8, 4, 2] },
{ "zwj-family", "👨\u200d👩\u200d👧", [18, 8, 5] },
{ "nul", "a\u0000b", [3, 3, 3] },
};
[Theory]
[MemberData(nameof(Cases))]
public void Lengths(string name, string s, int[] want)
{
Assert.NotNull(name);
Assert.Equal(want, StringLength.Lengths(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
const encoder = new TextEncoder();
/**
* Returns the length of s in UTF-8 bytes, in UTF-16 code units and in code
* points.
*/
export function lengths(s) {
// s.length counts UTF-16 code units. The string iterator yields code points.
return [encoder.encode(s).length, s.length, [...s].length];
}
stringLength.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { lengths } from "./stringLength.js";
const cases = [
["ascii", "hello", [5, 5, 5]],
["words", "Hello, world", [12, 12, 12]],
["two-byte", "naïve", [6, 5, 5]],
["three-byte", "日本語", [9, 3, 3]],
["cyrillic", "Привет", [12, 6, 6]],
["empty", "", [0, 0, 0]],
["single", "a", [1, 1, 1]],
["euro-sign", "€", [3, 1, 1]],
["astral", "🙂", [4, 2, 1]],
["mixed", "a🙂b", [6, 4, 3]],
["combining-mark", "e\u0301", [3, 2, 2]],
["precomposed", "é", [2, 1, 1]],
["flag", "🇫🇷", [8, 4, 2]],
["zwj-family", "👨\u200d👩\u200d👧", [18, 8, 5]],
["nul", "a\u0000b", [3, 3, 3]],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.deepEqual(lengths(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
const encoder = new TextEncoder();
/**
* Returns the length of s in UTF-8 bytes, in UTF-16 code units and in code
* points.
*/
export function lengths(s: string): [number, number, number] {
// s.length counts UTF-16 code units. The string iterator yields code points.
return [encoder.encode(s).length, s.length, [...s].length];
}
stringLength.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { lengths } from "./stringLength.ts";
const cases: [string, string, number[]][] = [
["ascii", "hello", [5, 5, 5]],
["words", "Hello, world", [12, 12, 12]],
["two-byte", "naïve", [6, 5, 5]],
["three-byte", "日本語", [9, 3, 3]],
["cyrillic", "Привет", [12, 6, 6]],
["empty", "", [0, 0, 0]],
["single", "a", [1, 1, 1]],
["euro-sign", "€", [3, 1, 1]],
["astral", "🙂", [4, 2, 1]],
["mixed", "a🙂b", [6, 4, 3]],
["combining-mark", "e\u0301", [3, 2, 2]],
["precomposed", "é", [2, 1, 1]],
["flag", "🇫🇷", [8, 4, 2]],
["zwj-family", "👨\u200d👩\u200d👧", [18, 8, 5]],
["nul", "a\u0000b", [3, 3, 3]],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.deepEqual(lengths(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
// Package length finds the lengths of a string in UTF-8 bytes, in UTF-16
// code units and in code points.
package length
import (
"unicode/utf16"
"unicode/utf8"
)
// Lengths returns the length of the UTF-8 string s in bytes, in UTF-16 code
// units and in code points.
func Lengths(s string) [3]int {
// A string is a sequence of bytes, and len counts them.
units := 0
for _, r := range s {
units += utf16.RuneLen(r)
}
return [3]int{len(s), units, utf8.RuneCountInString(s)}
}
string_length_test.go 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
package length
import "testing"
func TestLengths(t *testing.T) {
cases := []struct {
name, s string
want [3]int
}{
{"ascii", "hello", [3]int{5, 5, 5}},
{"words", "Hello, world", [3]int{12, 12, 12}},
{"two-byte", "naïve", [3]int{6, 5, 5}},
{"three-byte", "日本語", [3]int{9, 3, 3}},
{"cyrillic", "Привет", [3]int{12, 6, 6}},
{"empty", "", [3]int{0, 0, 0}},
{"single", "a", [3]int{1, 1, 1}},
{"euro-sign", "€", [3]int{3, 1, 1}},
{"astral", "🙂", [3]int{4, 2, 1}},
{"mixed", "a🙂b", [3]int{6, 4, 3}},
{"combining-mark", "e\u0301", [3]int{3, 2, 2}},
{"precomposed", "é", [3]int{2, 1, 1}},
{"flag", "🇫🇷", [3]int{8, 4, 2}},
{"zwj-family", "👨\u200d👩\u200d👧", [3]int{18, 8, 5}},
{"nul", "a\x00b", [3]int{3, 3, 3}},
}
for _, c := range cases {
if got := Lengths(c.s); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
//! Find the lengths of a string in UTF-8 bytes, in UTF-16 code units and in
//! code points.
/// Returns the length of `s` in UTF-8 bytes, in UTF-16 code units and in
/// code points.
pub fn lengths(s: &str) -> [usize; 3] {
// A str is UTF-8, so len counts bytes. chars yields code points.
[s.len(), s.encode_utf16().count(), s.chars().count()]
}
tests/string_length_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-length-of-a-string/.
use algo_find_the_length_of_a_string::lengths;
#[test]
fn cases() {
let cases: &[(&str, &str, [usize; 3])] = &[
("ascii", "hello", [5, 5, 5]),
("words", "Hello, world", [12, 12, 12]),
("two-byte", "naïve", [6, 5, 5]),
("three-byte", "日本語", [9, 3, 3]),
("cyrillic", "Привет", [12, 6, 6]),
("empty", "", [0, 0, 0]),
("single", "a", [1, 1, 1]),
("euro-sign", "€", [3, 1, 1]),
("astral", "🙂", [4, 2, 1]),
("mixed", "a🙂b", [6, 4, 3]),
("combining-mark", "e\u{301}", [3, 2, 2]),
("precomposed", "\u{e9}", [2, 1, 1]),
("flag", "🇫🇷", [8, 4, 2]),
("zwj-family", "👨\u{200d}👩\u{200d}👧", [18, 8, 5]),
("nul", "a\0b", [3, 3, 3]),
];
for (name, s, want) in cases {
assert_eq!(lengths(s), *want, "case {name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-length-of-a-string/.
# lengths S: prints three lengths of the valid UTF-8 string S on one line: the
# number of bytes, the number of UTF-16 code units and the number of code
# points. ${#s} counts characters in the current locale, so the function sets
# the locale for each count.
lengths() {
local s=$1 bytes code_points four_byte
# In the C locale each byte is one character.
bytes=$(LC_ALL=C; printf '%s' "${#s}")
# In a UTF-8 locale each code point is one character.
code_points=$(LC_ALL=C.UTF-8; printf '%s' "${#s}")
# A first byte F0 to F4 starts a code point above U+FFFF, and UTF-16 needs
# two code units for it. Keep only those bytes and count them.
four_byte=$(LC_ALL=C; t=${s//[!$'\xf0'-$'\xf4']/}; printf '%s' "${#t}")
printf '%d %d %d\n' "$bytes" $((code_points + four_byte)) "$code_points"
}
test_string_length.bats 33 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-length-of-a-string/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/string_length.sh"
}
check() { # check STRING WANT
run lengths "$1"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
@test "ascii" { check 'hello' '5 5 5'; }
@test "words" { check 'Hello, world' '12 12 12'; }
@test "two-byte" { check 'naïve' '6 5 5'; }
@test "three-byte" { check '日本語' '9 3 3'; }
@test "cyrillic" { check 'Привет' '12 6 6'; }
@test "empty" { check '' '0 0 0'; }
@test "single" { check 'a' '1 1 1'; }
@test "euro-sign" { check '€' '3 1 1'; }
@test "astral" { check '🙂' '4 2 1'; }
@test "mixed" { check 'a🙂b' '6 4 3'; }
# U+0301 COMBINING ACUTE ACCENT is CC 81 in UTF-8.
@test "combining-mark" { check $'e\xcc\x81' '3 2 2'; }
@test "precomposed" { check $'\xc3\xa9' '2 1 1'; }
@test "flag" { check '🇫🇷' '8 4 2'; }
# U+200D ZERO WIDTH JOINER is E2 80 8D in UTF-8.
@test "zwj-family" { check $'👨\xe2\x80\x8d👩\xe2\x80\x8d👧' '18 8 5'; }
# A Bash variable cannot hold a NUL character, so there is no nul case.
References
- F. Yergeau, RFC 3629, UTF-8, a transformation format of ISO 10646 (2003), Section 3, UTF-8 definition
- P. Hoffman and F. Yergeau, RFC 2781, UTF-16, an encoding of ISO 10646 (2000), Section 2.1, Encoding UTF-16
- The Python Standard Library, Built-in Types, Text Sequence Type, str
- The Python Standard Library, Built-in Functions, len
- MDN Web Docs, String length, Description
- MDN Web Docs, TextEncoder encode() method
- Java SE 25 API, java.lang.String, length(), codePointCount(int, int)
- .NET API reference, String.Length property, Remarks
- .NET API reference, Encoding.GetByteCount method
- .NET API reference, String.EnumerateRunes method
- The Go Programming Language Specification, String types
- Go standard library, package unicode/utf8, RuneCountInString
- Go standard library, package unicode/utf16, RuneLen
- The Rust Standard Library, primitive type str, len, chars, encode_utf16
- cppreference.com, strlen, strnlen_s
- cppreference.com, std::basic_string size, length
- Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Shell Parameter Expansion; Bash Variables, LC_CTYPE
- MDN Web Docs, Intl.Segmenter
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 MRBAQA Edit this page History Report an error Markdown