Taskintro
Iterate over the characters of a string
Also called loop over characters, for each character, iterate over code points, chars, runes, string iterator.
Visit each code point of a string in order, not each byte or each UTF-16 code unit.
- Evidence
- Code in 10 languages
Task
Visit each character of a string, from the start to the end. The function characters(s) returns a list with one string for each code point of s. For example, characters("abc") is ["a", "b", "c"], and characters("") is an empty list.
A character is a code point. An emoji above U+FFFF is one character, and a combining mark such as U+0301 is a character of its own. The loop must not give the bytes of a UTF-8 string or the UTF-16 code units of a string. To visit what a reader sees as one character, see Count the graphemes of a string.
Solutions
| Language | Loop over the code points |
|---|---|
| Python | for c in s |
| JavaScript, TypeScript | for (const c of s) or Array.from(s) |
| Java | s.codePoints() |
| C# | foreach (Rune r in s.EnumerateRunes()) |
| Go | for i, r := range s |
| Rust | for c in s.chars() |
| C | a loop that finds the length of each UTF-8 sequence from its first byte |
| C++ | the same loop, with std::string_view::substr |
| Bash | the same loop in the C locale, with ${s:i:n} |
- Python. "Strings are immutable sequences of Unicode code points"1. A loop over a
strgives one code point at each step. - JavaScript and TypeScript. "Strings are iterated by Unicode code points"2.
for...of,Array.fromand the spread syntax use this iterator. - Java.
codePoints()returns "a stream of code point values from this sequence"3. - C#.
EnumerateRunesreturns "an enumeration of Rune from this string"4. ARuneis one code point. - Go. A range loop over a string gives a rune at each step.
- Rust.
chars()gives eachchar, which is a code point. - C, C++ and Bash. A string is a sequence of bytes. In UTF-8, characters "are encoded using sequences of 1 to 4 octets"5. The first byte gives the length: 1 byte below 0x80, 2 bytes from 0xC0, 3 bytes from 0xE0 and 4 bytes from 0xF0.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
emptyandsingle: an empty string gives an empty list, and a string of one code point gives a list of one string.non-asciiandcjk:é(U+00E9) has 2 bytes in UTF-8, and each CJK character incjkhas 3 bytes. Each one is one character.astral: U+1F642 is one character, but it is 2 UTF-16 code units and 4 UTF-8 bytes.combining:eand U+0301 are 2 characters, but a reader sees oneé.regional-indicator: a flag is 2 regional indicators, U+1F1FA and U+1F1F8, so it is 2 characters.zwj: U+1F469, U+200D and U+1F4BB are 3 characters. U+200D is the zero width joiner.control: a tab and a line feed are characters of their own.
Pitfalls
- Python bytes give integers. For a
str, the loop gives code points, soeand U+0301 are 2 steps. Forbytes, "b[0] will be an integer"1, so the loop gives the byte values:
s = "e\u0301"
print([hex(ord(c)) for c in s])
print(list("h\u00e9".encode()))
['0x65', '0x301']
[104, 195, 169]
- JavaScript s[i] gives UTF-16 code units. An index loop with
s.lengthgives each half of a surrogate pair.for...ofgives whole code points:
const s = "a\u{1f642}";
const units = [];
for (let i = 0; i < s.length; i++) {
units.push(s.charCodeAt(i).toString(16));
}
console.log(units.join(" "));
const points = [];
for (const c of s) {
points.push(c.codePointAt(0).toString(16));
}
console.log(points.join(" "));
61 d83d de42
61 1f642
- Java charAt gives UTF-16 code units. "A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs"3. So a loop with
charAtgives 0xD83D and 0xDE42 for U+1F642:
public class Main {
public static void main(String[] args) {
String s = "a\uD83D\uDE42";
StringBuilder units = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
units.append(Integer.toHexString(s.charAt(i))).append(' ');
}
System.out.println(units.toString().trim());
StringBuilder points = new StringBuilder();
s.codePoints().forEach(c -> points.append(Integer.toHexString(c)).append(' '));
System.out.println(points.toString().trim());
}
}
61 d83d de42
61 1f642
- C# foreach over a string gives chars. A
charis a UTF-16 code unit. U+1F642 is 2 chars, and the second char is a surrogate:
using System;
using System.Linq;
string s = "a\U0001F642";
Console.WriteLine($"{s.Length} {s.EnumerateRunes().Count()} {char.IsSurrogate(s[1])}");
3 2 True
- Go s[i] gives bytes, and the range index is a byte index. In a range loop, "the index value will be the index of the first byte of successive UTF-8-encoded code points in the string"6. So the index goes 0, 1, 3, not 0, 1, 2:
package main
import (
"fmt"
"strings"
)
func main() {
s := "h\u00e9x"
var bytes, runes []string
for i := 0; i < len(s); i++ {
bytes = append(bytes, fmt.Sprintf("%x", s[i]))
}
for i, r := range s {
runes = append(runes, fmt.Sprintf("%d:%U", i, r))
}
fmt.Println(strings.Join(bytes, " "))
fmt.Println(strings.Join(runes, " "))
}
68 c3 a9 78
0:U+0068 1:U+00E9 3:U+0078
- Rust len counts bytes. For
len, "This length is in bytes, not chars or graphemes"7.char_indicesgives each char with its byte position, so the positions skip a number afteré:
fn main() {
let s = "h\u{e9}x";
println!("{} {}", s.len(), s.chars().count());
let offsets: Vec<usize> = s.char_indices().map(|(i, _)| i).collect();
println!("{:?}", offsets);
}
4 3
[0, 1, 3]
- C s[i] gives bytes. The loop over
handétakes 3 steps. To count code points, skip each continuation byte, which has the form10xxxxxx:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s = "h\xc3\xa9";
size_t points = 0;
for (size_t i = 0; s[i] != '\0'; i++) {
printf(i == 0 ? "%02x" : " %02x", (unsigned char)s[i]);
// A continuation byte has the form 10xxxxxx.
if (((unsigned char)s[i] & 0xc0) != 0x80) {
points++;
}
}
printf("\n%zu bytes, %zu code points\n", strlen(s), points);
return 0;
}
68 c3 a9
3 bytes, 2 code points
- C++ range for gives chars, and size counts them.
size()returns "the number of CharT elements in the string"8. For astd::string, aCharTis a byte, so U+1F642 takes 4 steps:
#include <iostream>
#include <string>
int main() {
std::string s = "a\xf0\x9f\x99\x82";
int steps = 0;
int points = 0;
for (char c : s) {
steps++;
if ((static_cast<unsigned char>(c) & 0xc0) != 0x80) {
points++;
}
}
std::cout << s.size() << " " << steps << " " << points << "\n";
}
5 5 2
- Bash
forover$sgives words. "The shell treats each character of$IFSas a delimiter, and splits the results of the other expansions into fields using these characters as field terminators"9. Sofor w in $sgives words, and the space is lost. Use an index loop with${s:i:1}:
s='a b'
for w in $s; do
printf '[%s]' "$w"
done
echo
for ((i = 0; i < ${#s}; i++)); do
printf '[%s]' "${s:i:1}"
done
echo
[a][b]
[a][ ][b]
Related tasks
- Find the length of a string: count the code points, the bytes or the code units.
- Get the code point of a character: get the number of each character that the loop gives.
- Count the graphemes of a string: visit what a reader sees as one character.
- Reverse a string: a loop over the characters in the other direction.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
def characters(s: str) -> list[str]:
"""Return the code points of s, each as a string of one code point.
A Python str is a sequence of code points, so iteration gives code points.
"""
return list(s)
test_characters.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
import pytest
from characters import characters
# A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
CASES = {
"ascii": ("abc", ["a", "b", "c"]),
"word": ("hello", ["h", "e", "l", "l", "o"]),
"space": ("a b", ["a", " ", "b"]),
"empty": ("", []),
"single": ("x", ["x"]),
"non-ascii": ("h\u00e9", ["h", "\u00e9"]),
"cjk": ("\u65e5\u672c", ["\u65e5", "\u672c"]),
"astral": ("a\U0001f642b", ["a", "\U0001f642", "b"]),
"combining": ("e\u0301", ["e", "\u0301"]),
"regional-indicator": ("\U0001f1fa\U0001f1f8", ["\U0001f1fa", "\U0001f1f8"]),
"zwj": ("\U0001f469\u200d\U0001f4bb", ["\U0001f469", "\u200d", "\U0001f4bb"]),
"control": ("a\tb\nc", ["a", "\t", "b", "\n", "c"]),
}
@pytest.mark.parametrize("name", CASES)
def test_characters(name):
s, want = CASES[name]
assert characters(s) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
#include "characters.hpp"
namespace {
// seq_len returns the length of the UTF-8 sequence that starts with the byte b.
// A range for loop over a std::string gives single bytes.
std::size_t seq_len(unsigned char b) {
if (b >= 0xf0) {
return 4;
}
if (b >= 0xe0) {
return 3;
}
if (b >= 0xc0) {
return 2;
}
return 1;
}
} // namespace
std::vector<std::string> characters(std::string_view s) {
std::vector<std::string> out;
std::size_t i = 0;
while (i < s.size()) {
std::size_t n = seq_len(static_cast<unsigned char>(s[i]));
out.emplace_back(s.substr(i, n));
i += n;
}
return out;
}
characters.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
#pragma once
#include <string>
#include <string_view>
#include <vector>
// characters returns the code points of the UTF-8 string s, each as a string.
std::vector<std::string> characters(std::string_view s);
test_characters.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
#include "characters.hpp"
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, std::string_view s, const std::vector<std::string> &want) {
if (characters(s) != want) {
std::cerr << "case " << name << " fails\n";
failures++;
}
}
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
int main() {
check("ascii", "abc", {"a", "b", "c"});
check("word", "hello", {"h", "e", "l", "l", "o"});
check("space", "a b", {"a", " ", "b"});
check("empty", "", {});
check("single", "x", {"x"});
check("non-ascii", "h\xc3\xa9", {"h", "\xc3\xa9"});
check("cjk", "\xe6\x97\xa5\xe6\x9c\xac", {"\xe6\x97\xa5", "\xe6\x9c\xac"});
check("astral", "a\xf0\x9f\x99\x82" "b", {"a", "\xf0\x9f\x99\x82", "b"});
check("combining", "e\xcc\x81", {"e", "\xcc\x81"});
check("regional-indicator", "\xf0\x9f\x87\xba\xf0\x9f\x87\xb8", {"\xf0\x9f\x87\xba", "\xf0\x9f\x87\xb8"});
check("zwj", "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb", {"\xf0\x9f\x91\xa9", "\xe2\x80\x8d", "\xf0\x9f\x92\xbb"});
check("control", "a\tb\nc", {"a", "\t", "b", "\n", "c"});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
import java.util.List;
final class Characters {
private Characters() {}
// characters returns the code points of s. A char is a UTF-16 code unit, so
// charAt would give each half of a surrogate pair. codePoints() gives whole
// code points.
static List<String> characters(String s) {
return s.codePoints().mapToObj(Character::toString).toList();
}
}
CharactersTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
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 CharactersTest {
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("ascii", "abc", List.of("a", "b", "c")),
Arguments.of("word", "hello", List.of("h", "e", "l", "l", "o")),
Arguments.of("space", "a b", List.of("a", " ", "b")),
Arguments.of("empty", "", List.of()),
Arguments.of("single", "x", List.of("x")),
Arguments.of("non-ascii", "h\u00e9", List.of("h", "\u00e9")),
Arguments.of("cjk", "\u65e5\u672c", List.of("\u65e5", "\u672c")),
Arguments.of("astral", "a\ud83d\ude42b", List.of("a", "\ud83d\ude42", "b")),
Arguments.of("combining", "e\u0301", List.of("e", "\u0301")),
Arguments.of("regional-indicator", "\ud83c\uddfa\ud83c\uddf8", List.of("\ud83c\uddfa", "\ud83c\uddf8")),
Arguments.of("zwj", "\ud83d\udc69\u200d\ud83d\udcbb", List.of("\ud83d\udc69", "\u200d", "\ud83d\udcbb")),
Arguments.of("control", "a\tb\nc", List.of("a", "\t", "b", "\n", "c")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void characters(String name, String s, List<String> want) {
assertEquals(want, Characters.characters(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
#include "characters.h"
#include <string.h>
// seq_len returns the length of the UTF-8 sequence that starts with the byte b.
// An index loop, s[i], would give single bytes, and a code point above U+007F
// has 2 to 4 bytes.
static size_t seq_len(unsigned char b) {
if (b >= 0xf0) {
return 4;
}
if (b >= 0xe0) {
return 3;
}
if (b >= 0xc0) {
return 2;
}
return 1;
}
char **characters(const char *s, size_t *n) {
// Each code point has at least one byte, so strlen(s) slots are enough.
char **out = malloc((strlen(s) + 1) * sizeof *out);
*n = 0;
if (out == NULL) {
return NULL;
}
while (*s != '\0') {
size_t len = seq_len((unsigned char)*s);
char *c = malloc(len + 1);
if (c == NULL) {
free_characters(out, *n);
*n = 0;
return NULL;
}
memcpy(c, s, len);
c[len] = '\0';
out[(*n)++] = c;
s += len;
}
return out;
}
void free_characters(char **chars, size_t n) {
if (chars == NULL) {
return;
}
for (size_t i = 0; i < n; i++) {
free(chars[i]);
}
free(chars);
}
characters.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
#ifndef CHARACTERS_H
#define CHARACTERS_H
#include <stdlib.h>
// characters returns a new array of *n new strings, one for each code point of
// the UTF-8 string s, or NULL if there is no memory. Free it with
// free_characters.
char **characters(const char *s, size_t *n);
void free_characters(char **chars, size_t n);
#endif
test_characters.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
#include "characters.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
// check compares the n strings of got with want, and then frees got.
static void check(const char *name, const char *s, const char *const *want, size_t n) {
size_t k = 0;
char **got = characters(s, &k);
if (got == NULL || k != n) {
fprintf(stderr, "case %s: got %zu characters, want %zu\n", name, k, n);
failures++;
} else {
for (size_t i = 0; i < n; i++) {
if (strcmp(got[i], want[i]) != 0) {
fprintf(stderr, "case %s: character %zu is wrong\n", name, i);
failures++;
break;
}
}
}
free_characters(got, k);
}
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
int main(void) {
check("ascii", "abc", (const char *const[]){"a", "b", "c"}, 3);
check("word", "hello", (const char *const[]){"h", "e", "l", "l", "o"}, 5);
check("space", "a b", (const char *const[]){"a", " ", "b"}, 3);
check("empty", "", (const char *const[]){NULL}, 0);
check("single", "x", (const char *const[]){"x"}, 1);
check("non-ascii", "h\xc3\xa9", (const char *const[]){"h", "\xc3\xa9"}, 2);
check("cjk", "\xe6\x97\xa5\xe6\x9c\xac", (const char *const[]){"\xe6\x97\xa5", "\xe6\x9c\xac"}, 2);
check("astral", "a\xf0\x9f\x99\x82" "b", (const char *const[]){"a", "\xf0\x9f\x99\x82", "b"}, 3);
check("combining", "e\xcc\x81", (const char *const[]){"e", "\xcc\x81"}, 2);
check("regional-indicator", "\xf0\x9f\x87\xba\xf0\x9f\x87\xb8", (const char *const[]){"\xf0\x9f\x87\xba", "\xf0\x9f\x87\xb8"}, 2);
check("zwj", "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb", (const char *const[]){"\xf0\x9f\x91\xa9", "\xe2\x80\x8d", "\xf0\x9f\x92\xbb"}, 3);
check("control", "a\tb\nc", (const char *const[]){"a", "\t", "b", "\n", "c"}, 5);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
using System.Collections.Generic;
using System.Text;
public static class StringCharacters
{
// Characters returns the code points of s. A char is a UTF-16 code unit,
// so foreach over the string would give each half of a surrogate pair.
// EnumerateRunes gives whole code points.
public static string[] Characters(string s)
{
var list = new List<string>();
foreach (Rune r in s.EnumerateRunes())
{
list.Add(r.ToString());
}
return list.ToArray();
}
}
CharactersTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
using Xunit;
public sealed class CharactersTests
{
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
public static TheoryData<string, string, string[]> Cases => new()
{
{ "ascii", "abc", new string[] { "a", "b", "c" } },
{ "word", "hello", new string[] { "h", "e", "l", "l", "o" } },
{ "space", "a b", new string[] { "a", " ", "b" } },
{ "empty", "", new string[] { } },
{ "single", "x", new string[] { "x" } },
{ "non-ascii", "h\u00e9", new string[] { "h", "\u00e9" } },
{ "cjk", "\u65e5\u672c", new string[] { "\u65e5", "\u672c" } },
{ "astral", "a\U0001f642b", new string[] { "a", "\U0001f642", "b" } },
{ "combining", "e\u0301", new string[] { "e", "\u0301" } },
{ "regional-indicator", "\U0001f1fa\U0001f1f8", new string[] { "\U0001f1fa", "\U0001f1f8" } },
{ "zwj", "\U0001f469\u200d\U0001f4bb", new string[] { "\U0001f469", "\u200d", "\U0001f4bb" } },
{ "control", "a\tb\nc", new string[] { "a", "\t", "b", "\n", "c" } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Characters(string name, string s, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, StringCharacters.Characters(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
// characters returns the code points of s. The string iterator gives code
// points, so U+1F642 is one element. s.split("") would give UTF-16 code units.
export function characters(s) {
return Array.from(s);
}
characters.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { characters } from "./characters.js";
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
const cases = [
["ascii", "abc", ["a", "b", "c"]],
["word", "hello", ["h", "e", "l", "l", "o"]],
["space", "a b", ["a", " ", "b"]],
["empty", "", []],
["single", "x", ["x"]],
["non-ascii", "h\u00e9", ["h", "\u00e9"]],
["cjk", "\u65e5\u672c", ["\u65e5", "\u672c"]],
["astral", "a\u{1f642}b", ["a", "\u{1f642}", "b"]],
["combining", "e\u0301", ["e", "\u0301"]],
["regional-indicator", "\u{1f1fa}\u{1f1f8}", ["\u{1f1fa}", "\u{1f1f8}"]],
["zwj", "\u{1f469}\u200d\u{1f4bb}", ["\u{1f469}", "\u200d", "\u{1f4bb}"]],
["control", "a\tb\nc", ["a", "\t", "b", "\n", "c"]],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.deepEqual(characters(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
// characters returns the code points of s. The string iterator gives code
// points, so U+1F642 is one element. s.split("") would give UTF-16 code units.
export function characters(s: string): string[] {
return Array.from(s);
}
characters.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { characters } from "./characters.ts";
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
const cases: [string, string, string[]][] = [
["ascii", "abc", ["a", "b", "c"]],
["word", "hello", ["h", "e", "l", "l", "o"]],
["space", "a b", ["a", " ", "b"]],
["empty", "", []],
["single", "x", ["x"]],
["non-ascii", "h\u00e9", ["h", "\u00e9"]],
["cjk", "\u65e5\u672c", ["\u65e5", "\u672c"]],
["astral", "a\u{1f642}b", ["a", "\u{1f642}", "b"]],
["combining", "e\u0301", ["e", "\u0301"]],
["regional-indicator", "\u{1f1fa}\u{1f1f8}", ["\u{1f1fa}", "\u{1f1f8}"]],
["zwj", "\u{1f469}\u200d\u{1f4bb}", ["\u{1f469}", "\u200d", "\u{1f4bb}"]],
["control", "a\tb\nc", ["a", "\t", "b", "\n", "c"]],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.deepEqual(characters(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
// Package characters gives the code points of a string.
package characters
// Characters returns the code points of s. A range loop over a string decodes
// one rune at each step. An index loop, s[i], would give single bytes.
func Characters(s string) []string {
out := []string{}
for _, r := range s {
out = append(out, string(r))
}
return out
}
characters_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
package characters
import (
"slices"
"testing"
)
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
var cases = []struct {
name, s string
want []string
}{
{"ascii", "abc", []string{"a", "b", "c"}},
{"word", "hello", []string{"h", "e", "l", "l", "o"}},
{"space", "a b", []string{"a", " ", "b"}},
{"empty", "", []string{}},
{"single", "x", []string{"x"}},
{"non-ascii", "h\u00e9", []string{"h", "\u00e9"}},
{"cjk", "\u65e5\u672c", []string{"\u65e5", "\u672c"}},
{"astral", "a\U0001f642b", []string{"a", "\U0001f642", "b"}},
{"combining", "e\u0301", []string{"e", "\u0301"}},
{"regional-indicator", "\U0001f1fa\U0001f1f8", []string{"\U0001f1fa", "\U0001f1f8"}},
{"zwj", "\U0001f469\u200d\U0001f4bb", []string{"\U0001f469", "\u200d", "\U0001f4bb"}},
{"control", "a\tb\nc", []string{"a", "\t", "b", "\n", "c"}},
}
func TestCharacters(t *testing.T) {
for _, c := range cases {
if got := Characters(c.s); !slices.Equal(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/iterate-over-the-characters-of-a-string/.
/// Returns the code points of `s`. `chars()` gives each `char`, which is a
/// code point. `bytes()` would give the UTF-8 bytes.
pub fn characters(s: &str) -> Vec<String> {
s.chars().map(String::from).collect()
}
tests/characters_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
use algo_iterate_over_the_characters_of_a_string::characters;
// A character is a code point. U+1F642 is one character, but two UTF-16 code units and four UTF-8 bytes. A combining mark, a ZWJ and each regional indicator is a character of its own.
#[test]
fn cases() {
let cases: [(&str, &str, &[&str]); 12] = [
("ascii", "abc", &["a", "b", "c"]),
("word", "hello", &["h", "e", "l", "l", "o"]),
("space", "a b", &["a", " ", "b"]),
("empty", "", &[]),
("single", "x", &["x"]),
("non-ascii", "h\u{e9}", &["h", "\u{e9}"]),
("cjk", "\u{65e5}\u{672c}", &["\u{65e5}", "\u{672c}"]),
("astral", "a\u{1f642}b", &["a", "\u{1f642}", "b"]),
("combining", "e\u{301}", &["e", "\u{301}"]),
("regional-indicator", "\u{1f1fa}\u{1f1f8}", &["\u{1f1fa}", "\u{1f1f8}"]),
("zwj", "\u{1f469}\u{200d}\u{1f4bb}", &["\u{1f469}", "\u{200d}", "\u{1f4bb}"]),
("control", "a\tb\nc", &["a", "\t", "b", "\n", "c"]),
];
for (name, s, want) in cases {
assert_eq!(characters(s), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
# characters S: sets the array CHARS to the code points of S. In the C locale,
# ${s:i:1} is one byte, so the loop finds the length of each UTF-8 sequence
# from its first byte. local LC_ALL=C keeps the change of locale inside the
# function.
characters() {
local LC_ALL=C
local s=$1 i=0 n b
CHARS=()
while ((i < ${#s})); do
b=${s:i:1}
n=1
if [[ $b > $'\xef' ]]; then
n=4
elif [[ $b > $'\xdf' ]]; then
n=3
elif [[ $b > $'\x7f' ]]; then
n=2
fi
CHARS+=("${s:i:n}")
((i += n))
done
}
test_characters.bats 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-the-characters-of-a-string/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/characters.sh"
}
check() { # check S WANT...: characters S must give the arguments after S
characters "$1"
shift
[ "${#CHARS[@]}" -eq "$#" ]
local i=0
for c in "$@"; do
[ "${CHARS[i]}" = "$c" ]
((i += 1))
done
}
# Each argument is a string of UTF-8 bytes, and each element of CHARS is one whole code point.
@test "ascii" { check 'abc' 'a' 'b' 'c'; }
@test "word" { check 'hello' 'h' 'e' 'l' 'l' 'o'; }
@test "space" { check 'a b' 'a' ' ' 'b'; }
@test "empty" { check ''; }
@test "single" { check 'x' 'x'; }
@test "non-ascii" { check $'h\xc3\xa9' 'h' $'\xc3\xa9'; }
@test "cjk" { check $'\xe6\x97\xa5\xe6\x9c\xac' $'\xe6\x97\xa5' $'\xe6\x9c\xac'; }
@test "astral" { check $'a\xf0\x9f\x99\x82b' 'a' $'\xf0\x9f\x99\x82' 'b'; }
@test "combining" { check $'e\xcc\x81' 'e' $'\xcc\x81'; }
@test "regional-indicator" { check $'\xf0\x9f\x87\xba\xf0\x9f\x87\xb8' $'\xf0\x9f\x87\xba' $'\xf0\x9f\x87\xb8'; }
@test "zwj" { check $'\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb' $'\xf0\x9f\x91\xa9' $'\xe2\x80\x8d' $'\xf0\x9f\x92\xbb'; }
@test "control" { check $'a\tb\nc' 'a' $'\t' 'b' $'\n' 'c'; }
References
- The Python Standard Library, Built-in Types, Text Sequence Type, str; Bytes Objects
- MDN Web Docs, String.prototype[Symbol.iterator](), Description
- Java SE 25 API, Class String, class description, codePoints()
- .NET API reference, String.EnumerateRunes method, Definition
- RFC 3629, UTF-8, a transformation format of ISO 10646, 3. UTF-8 definition
- The Go Programming Language Specification, For statements with range clause
- Rust standard library, primitive type str, len, chars, char_indices
- cppreference.com, std::basic_string::size, length, Return value
- Bash Reference Manual, 3.5.7 Word Splitting
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 ZHK7ZJ Edit this page History Report an error Markdown