Programming Search⌘K

Taskintro

Get a substring

Also called substring, slice a string, substr, string slice, cut a string, part of a string.

Get the part of a string between two indexes, know which unit each language counts, and know what happens when an index is out of range or falls inside a character.

Task

Get the part of a string from one index up to a second index. The function substring(s, start, end) returns the code points of s at the indexes start to end - 1. The range is half-open, so end - start is the length of the result, and start = end gives the empty string. For example, substring("Hello, world", 7, 12) is "world".

The indexes count code points, so the result is the same in every language. The built-in operations of most languages count other units. Python counts code points1, and Go, Rust, C and C++ count bytes of UTF-8. In JavaScript, "Strings are represented fundamentally as sequences of UTF-16 code units"2. A Java String is "a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs"3, and a C# char "Represents a character as a UTF-16 code unit"4. For ASCII text, all of these units are the same. For other text, an index in bytes or code units can fall inside a character.

Solutions

Language Built-in operation Unit of the built-in The code
Python s[start:end] code point the slice
JavaScript, TypeScript s.slice(start, end) UTF-16 code unit Array.from(s), then slice and join
Java s.substring(begin, end) UTF-16 code unit offsetByCodePoints, then substring
C# s.Substring(start, length), s[start..end] UTF-16 code unit an offset loop, then s[from..to]
Go s[low:high] byte an offset loop with range, then s[i:j]
Rust &s[a..b], s.get(a..b) byte char_indices().nth(k), then s[i..j]
C memcpy byte an offset loop, then malloc and memcpy
C++ s.substr(pos, count) byte an offset loop, then substr
Bash ${s:offset:length} character of the locale the expansion with LC_ALL=C.UTF-8
  • Python. "Strings are immutable sequences of Unicode code points"1, so s[start:end] is the answer. The slice is "the sequence of items with index k such that i <= k < j"1.
  • JavaScript and TypeScript. slice and substring count UTF-16 code units, so they can cut an emoji in two. The code makes an array of the code points with Array.from(s), slices the array and joins it.
  • Java. substring(begin, end) "begins at the specified beginIndex and extends to the character at index endIndex - 1"3, and it counts char values. offsetByCodePoints "Returns the index within this String that is offset from the given index by codePointOffset code points"3, so the code converts each index with it first.
  • C#. Substring "starts at a specified character position and has a specified length"5. A char is one UTF-16 code unit4, so the code walks the string, skips one more unit at each surrogate pair, and then uses the range s[from..to].
  • Go. "For arrays or strings, the indices are in range if 0 <= low <= high <= len(a)"6, and len counts bytes. For a string, a range loop "iterates over the Unicode code points in the string starting at byte index 0"6, so the code uses a range loop to find the byte index of each code point index.
  • Rust. char_indices "Returns an iterator over the chars of a string slice, and their positions"7. The code takes the byte position of the code point start and of the code point end, and slices between them. The end of the string is a valid position.
  • C. A char * holds bytes of UTF-8. In UTF-8, each byte after the first byte of a code point has the form 10xxxxxx8, so "Character boundaries are easily found from anywhere in an octet stream"8. The code counts the bytes that do not have this form to find each offset, copies the bytes with memcpy into a new allocation and adds the null byte. The caller frees the result.
  • C++. The code finds the two byte offsets in the same way and calls substr with a position and a count.
  • Bash. ${parameter:offset:length} "expands to up to length characters of the value of parameter starting at the character specified by offset"9. The function runs the expansion in a subshell with LC_ALL=C.UTF-8, where each code point is one character.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: the empty string with start = end = 0 gives the empty string.
  • whole and at-end: end can be the length of the string. An index equal to the length is valid, and an index larger than it is outside the contract.
  • empty-range: start = end in the middle of the string gives the empty string.
  • non-ascii: in naïve café, the letter ï is 2 bytes in UTF-8, so an index in bytes and an index in code points are not the same after it. The CJK case has 3 bytes for each character.
  • astral and astral-only: an emoji such as 🙂 is one code point, 4 bytes of UTF-8 and 2 UTF-16 code units. A solution that counts code units fails these cases.
  • combining and combining-mark: e\u0301 is the letter e and a combining accent, which are 2 code points. A cut between them is valid in this contract, and the result starts with the mark. To keep each character that a reader sees whole, count graphemes, as in Count the graphemes of a string.

Pitfalls

  • Python slices do not check the range. "If i or j is greater than len(s), use len(s)"1, so a slice past the end is shorter than you asked, or empty. An index of one item raises IndexError:
s = "abc"
print(repr(s[1:10]), repr(s[5:9]), repr(s[-2:]))
try:
    s[5]
except IndexError as e:
    print("IndexError:", e)
Output
'bc' '' 'bc'
IndexError: string index out of range
  • JavaScript slice and substring are not the same. For slice, "If indexStart < 0, the index is counted from the end of the string"10, and an end before the start gives the empty string. For substring, "If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped"11, and a negative index is 0. Both count code units, so a cut after 2 units of a string with an emoji keeps half of the emoji, and the result is not well formed:
const s = "abc";
console.log(s.slice(2, 0), "|", s.substring(2, 0));
console.log(s.slice(-2), "|", s.substring(-2));
const t = "a\u{1F642}";
const cut = t.slice(0, 2);
console.log(cut.length, cut.isWellFormed());
Output
 | ab
bc | abc
2 false
  • Java substring throws when the end is past the length. It throws an exception "if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex"3. The cut can also fall between the two halves of a surrogate pair:
public class Main {
  public static void main(String[] args) {
    String s = "Hello, world";
    System.out.println(s.substring(7, 12));
    try {
      s.substring(7, 20);
    } catch (StringIndexOutOfBoundsException e) {
      System.out.println("StringIndexOutOfBoundsException");
    }
    String t = "a🙂";
    String cut = t.substring(0, 2);
    System.out.println(cut.length() + " " + Character.isHighSurrogate(cut.charAt(1)));
  }
}
Output
world
StringIndexOutOfBoundsException
2 true
  • C# Substring takes a length, not an end. s.Substring(7, 5) and the range s[7..12] give the same result. A call with an end index in place of the length throws ArgumentOutOfRangeException when "startIndex plus length indicates a position not within this instance"5:
string s = "Hello, world";
Console.WriteLine(s.Substring(7, 5));
Console.WriteLine(s[7..12]);
try
{
    Console.WriteLine(s.Substring(7, 12));
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("ArgumentOutOfRangeException");
}
Output
world
world
ArgumentOutOfRangeException
  • Go slices a string by bytes. s[0:3] of naïve keeps the first byte of ï only, and the result is not valid UTF-8. Convert to []rune to count code points. "If the indices are out of range at run time, a run-time panic occurs"6:
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	s := "naïve"
	cut := s[0:3]
	fmt.Printf("%q %v\n", cut, utf8.ValidString(cut))
	r := []rune(s)
	fmt.Println(string(r[0:3]))
	defer func() { fmt.Println("panic:", recover()) }()
	i := 9
	fmt.Println(s[2:i])
}
Output
"na\xc3" false
naï
panic: runtime error: slice bounds out of range [:9] with length 6
  • Rust panics on a byte index inside a character. is_char_boundary "Checks that index-th byte is the first byte in a UTF-8 code point sequence or the end of the string"7. Index 3 of naïve is not a boundary. get "Returns None whenever equivalent indexing operation would panic"7:
fn main() {
    let s = "naïve";
    println!("{:?}", (0..=s.len()).filter(|&i| s.is_char_boundary(i)).collect::<Vec<_>>());
    println!("{:?} {:?}", s.get(0..3), s.get(0..4));
    let t: String = s.chars().skip(2).take(3).collect();
    println!("{t}");
}
Output
[0, 1, 2, 4, 5, 6]
None Some("naï")
ïve
  • C strncpy does not always add the null byte. "If count is reached before the entire array src was copied, the resulting character array is not null-terminated"12. Add the null byte yourself. To print part of a string with no copy, give printf a precision with %.*s:
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "Hello, world";
    printf("%.*s\n", 5, s + 7);
    char d[6];
    memset(d, 'z', sizeof d);
    strncpy(d, s, 3);
    printf("d[3] is '%c', not a null byte\n", d[3]);
    d[3] = '\0';
    printf("%s\n", d);
}
Output
world
d[3] is 'z', not a null byte
Hel
  • C++ substr takes a count, not an end. "If the requested substring extends past the end of the string"13, the result stops at the end, so substr(7, 12) works and hides the mistake. A position past the end throws std::out_of_range13:
#include <print>
#include <stdexcept>
#include <string>

int main() {
    std::string s = "Hello, world";
    std::println("{}", s.substr(7, 12));
    std::println("{}", s.substr(7, 5));
    try {
        s.substr(13);
    } catch (const std::out_of_range &) {
        std::println("std::out_of_range");
    }
}
Output
world
world
std::out_of_range
  • Bash needs a space before a negative offset. "a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion"9. Without the space, ${s:-3} is the default value expansion, and it gives all of Hello:
s=Hello
echo "${s:1:3}"
echo "${s: -3}"
echo "${s:-3}"
echo "${s:(-3):2}"
Output
ell
llo
Hello
ll

Code

The build runs the native tests of each language in a pinned toolchain.

substring.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-substring/.


def substring(s: str, start: int, end: int) -> str:
    """Return the code points of s from index start up to, not including, end."""
    # A str is a sequence of code points, so a slice cuts at code points.
    return s[start:end]
test_substring.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-substring/.

import pytest

from substring import substring

# U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
CASES = {
    "middle": ("Hello, world", 7, 12, "world"),
    "prefix": ("Hello, world", 0, 5, "Hello"),
    "one-char": ("abc", 1, 2, "b"),
    "empty": ("", 0, 0, ""),
    "whole": ("abc", 0, 3, "abc"),
    "empty-range": ("abc", 1, 1, ""),
    "at-end": ("abc", 3, 3, ""),
    "non-ascii": ("naïve café", 2, 5, "ïve"),
    "cjk": ("日本語テキスト", 3, 7, "テキスト"),
    "astral": ("a\U0001f642b\U0001f643c", 1, 4, "\U0001f642b\U0001f643"),
    "astral-only": ("\U0001f642\U0001f643", 1, 2, "\U0001f643"),
    "combining": ("e\u0301t\u00e9", 0, 1, "e"),
    "combining-mark": ("e\u0301t\u00e9", 1, 3, "\u0301t"),
}


@pytest.mark.parametrize("name", CASES)
def test_substring(name):
    s, start, end, want = CASES[name]
    assert substring(s, start, end) == want
substring.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

#include "substring.hpp"

namespace {

// offset returns the byte index of code point k in s, or s.size() for the
// end. A byte of the form 10xxxxxx continues a code point.
std::size_t offset(std::string_view s, std::size_t k) {
    std::size_t n = 0;
    for (std::size_t i = 0; i < s.size(); i++) {
        if ((static_cast<unsigned char>(s[i]) & 0xC0) != 0x80) {
            if (n == k) {
                return i;
            }
            n++;
        }
    }
    return s.size();
}

}  // namespace

std::string substring(std::string_view s, std::size_t start, std::size_t end) {
    // substr takes a start and a count of char elements, which are bytes.
    std::size_t from = offset(s, start);
    return std::string(s.substr(from, offset(s, end) - from));
}
substring.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

#pragma once

#include <cstddef>
#include <string>
#include <string_view>

// substring returns the code points of the UTF-8 string s from index start up
// to, not including, end.
std::string substring(std::string_view s, std::size_t start, std::size_t end);
test_substring.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

#include "substring.hpp"

#include <iostream>
#include <string_view>

static int failures = 0;

static void check(std::string_view name, std::string_view s, std::size_t start, std::size_t end, std::string_view want) {
    std::string got = substring(s, start, end);
    if (got != want) {
        std::cerr << "case " << name << ": got [" << got << "], want [" << want << "]\n";
        failures++;
    }
}

int main() {
    check("middle", "Hello, world", 7, 12, "world");
    check("prefix", "Hello, world", 0, 5, "Hello");
    check("one-char", "abc", 1, 2, "b");
    check("empty", "", 0, 0, "");
    check("whole", "abc", 0, 3, "abc");
    check("empty-range", "abc", 1, 1, "");
    check("at-end", "abc", 3, 3, "");
    check("non-ascii", "naïve café", 2, 5, "ïve");
    check("cjk", "日本語テキスト", 3, 7, "テキスト");
    check("astral", "a\U0001F642b\U0001F643c", 1, 4, "\U0001F642b\U0001F643");
    check("astral-only", "\U0001F642\U0001F643", 1, 2, "\U0001F643");
    // U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
    check("combining", "e\u0301t\u00e9", 0, 1, "e");
    check("combining-mark", "e\u0301t\u00e9", 1, 3, "\u0301t");
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Substring.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

/** Gets a substring by code point indexes. */
public final class Substring {
  private Substring() {}

  /** Returns the code points of s from index start up to, not including, end. */
  public static String substring(String s, int start, int end) {
    // String.substring takes char indexes, which are UTF-16 code units, so
    // the code converts the code point indexes first.
    int from = s.offsetByCodePoints(0, start);
    int to = s.offsetByCodePoints(from, end - start);
    return s.substring(from, to);
  }
}
SubstringTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

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 SubstringTest {
  // U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("middle", "Hello, world", 7, 12, "world"),
        Arguments.of("prefix", "Hello, world", 0, 5, "Hello"),
        Arguments.of("one-char", "abc", 1, 2, "b"),
        Arguments.of("empty", "", 0, 0, ""),
        Arguments.of("whole", "abc", 0, 3, "abc"),
        Arguments.of("empty-range", "abc", 1, 1, ""),
        Arguments.of("at-end", "abc", 3, 3, ""),
        Arguments.of("non-ascii", "naïve café", 2, 5, "ïve"),
        Arguments.of("cjk", "日本語テキスト", 3, 7, "テキスト"),
        Arguments.of("astral", "a\uD83D\uDE42b\uD83D\uDE43c", 1, 4, "\uD83D\uDE42b\uD83D\uDE43"),
        Arguments.of("astral-only", "\uD83D\uDE42\uD83D\uDE43", 1, 2, "\uD83D\uDE43"),
        Arguments.of("combining", "e\u0301t\u00e9", 0, 1, "e"),
        Arguments.of("combining-mark", "e\u0301t\u00e9", 1, 3, "\u0301t"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void substring(String name, String s, int start, int end, String want) {
    assertEquals(want, Substring.substring(s, start, end));
  }
}
substring.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

#include "substring.h"

#include <stdlib.h>
#include <string.h>

// offset returns the byte index of code point k in s, or strlen(s) for the
// end. A byte of the form 10xxxxxx continues a code point, and every other
// byte starts one.
static size_t offset(const char *s, size_t k) {
    size_t n = 0;
    size_t i = 0;
    for (; s[i] != '\0'; i++) {
        if (((unsigned char)s[i] & 0xC0) != 0x80) {
            if (n == k) {
                return i;
            }
            n++;
        }
    }
    return i;
}

char *substring(const char *s, size_t start, size_t end) {
    size_t from = offset(s, start);
    size_t to = offset(s, end);
    char *r = malloc(to - from + 1);
    if (r == NULL) {
        return NULL;
    }
    memcpy(r, s + from, to - from);
    r[to - from] = '\0';
    return r;
}
substring.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

#ifndef SUBSTRING_H
#define SUBSTRING_H

#include <stddef.h>

// substring returns the code points of the UTF-8 string s from index start up
// to, not including, end, in a new string that the caller frees. It returns
// NULL if the allocation fails.
char *substring(const char *s, size_t start, size_t end);

#endif
test_substring.c 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

#include "substring.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, const char *s, size_t start, size_t end, const char *want) {
    char *got = substring(s, start, end);
    if (got == NULL || strcmp(got, want) != 0) {
        fprintf(stderr, "case %s: got [%s], want [%s]\n", name, got ? got : "NULL", want);
        failures++;
    }
    free(got);
}

// The strings are UTF-8 bytes: C3 AF is U+00EF, C3 A9 is U+00E9, CC 81 is
// U+0301 COMBINING ACUTE ACCENT, and F0 9F 99 82 and F0 9F 99 83 are U+1F642
// and U+1F643.
int main(void) {
    check("middle", "Hello, world", 7, 12, "world");
    check("prefix", "Hello, world", 0, 5, "Hello");
    check("one-char", "abc", 1, 2, "b");
    check("empty", "", 0, 0, "");
    check("whole", "abc", 0, 3, "abc");
    check("empty-range", "abc", 1, 1, "");
    check("at-end", "abc", 3, 3, "");
    check("non-ascii", "na\xc3\xafve caf\xc3\xa9", 2, 5, "\xc3\xafve");
    check("cjk", "日本語テキスト", 3, 7, "テキスト");
    check("astral", "a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x83" "c", 1, 4, "\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x83");
    check("astral-only", "\xf0\x9f\x99\x82\xf0\x9f\x99\x83", 1, 2, "\xf0\x9f\x99\x83");
    check("combining", "e\xcc\x81t\xc3\xa9", 0, 1, "e");
    check("combining-mark", "e\xcc\x81t\xc3\xa9", 1, 3, "\xcc\x81t");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Substring.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

public static class Substring
{
    /// <summary>Returns the code points of s from index start up to, not including, end.</summary>
    public static string Get(string s, int start, int end)
    {
        // string.Substring takes char indexes, which are UTF-16 code units,
        // so the code converts the code point indexes first.
        int from = Offset(s, 0, start);
        int to = Offset(s, from, end - start);
        return s[from..to];
    }

    // Offset returns the char index that is count code points after index i.
    private static int Offset(string s, int i, int count)
    {
        for (int k = 0; k < count; k++)
        {
            i += char.IsSurrogatePair(s, i) ? 2 : 1;
        }
        return i;
    }
}
SubstringTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

using Xunit;

public sealed class SubstringTests
{
    // U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
    public static TheoryData<string, string, int, int, string> Cases => new()
    {
        { "middle", "Hello, world", 7, 12, "world" },
        { "prefix", "Hello, world", 0, 5, "Hello" },
        { "one-char", "abc", 1, 2, "b" },
        { "empty", "", 0, 0, "" },
        { "whole", "abc", 0, 3, "abc" },
        { "empty-range", "abc", 1, 1, "" },
        { "at-end", "abc", 3, 3, "" },
        { "non-ascii", "naïve café", 2, 5, "ïve" },
        { "cjk", "日本語テキスト", 3, 7, "テキスト" },
        { "astral", "a\U0001F642b\U0001F643c", 1, 4, "\U0001F642b\U0001F643" },
        { "astral-only", "\U0001F642\U0001F643", 1, 2, "\U0001F643" },
        { "combining", "e\u0301t\u00e9", 0, 1, "e" },
        { "combining-mark", "e\u0301t\u00e9", 1, 3, "\u0301t" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Get(string name, string s, int start, int end, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Substring.Get(s, start, end));
    }
}
substring.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

/**
 * Returns the code points of s from index start up to, not including, end.
 * @param {string} s
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
export function substring(s, start, end) {
  // s.slice counts UTF-16 code units. The string iterator yields code
  // points, so the code slices the array of code points.
  return Array.from(s).slice(start, end).join("");
}
substring.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { substring } from "./substring.js";

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const cases = [
  ["middle", "Hello, world", 7, 12, "world"],
  ["prefix", "Hello, world", 0, 5, "Hello"],
  ["one-char", "abc", 1, 2, "b"],
  ["empty", "", 0, 0, ""],
  ["whole", "abc", 0, 3, "abc"],
  ["empty-range", "abc", 1, 1, ""],
  ["at-end", "abc", 3, 3, ""],
  ["non-ascii", "naïve café", 2, 5, "ïve"],
  ["cjk", "日本語テキスト", 3, 7, "テキスト"],
  ["astral", "a\u{1F642}b\u{1F643}c", 1, 4, "\u{1F642}b\u{1F643}"],
  ["astral-only", "\u{1F642}\u{1F643}", 1, 2, "\u{1F643}"],
  ["combining", "e\u0301t\u00e9", 0, 1, "e"],
  ["combining-mark", "e\u0301t\u00e9", 1, 3, "\u0301t"],
];

for (const [name, s, start, end, want] of cases) {
  test(name, () => {
    assert.equal(substring(s, start, end), want);
  });
}
substring.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

/** Returns the code points of s from index start up to, not including, end. */
export function substring(s: string, start: number, end: number): string {
  // s.slice counts UTF-16 code units. The string iterator yields code
  // points, so the code slices the array of code points.
  return Array.from(s).slice(start, end).join("");
}
substring.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { substring } from "./substring.ts";

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const cases: [string, string, number, number, string][] = [
  ["middle", "Hello, world", 7, 12, "world"],
  ["prefix", "Hello, world", 0, 5, "Hello"],
  ["one-char", "abc", 1, 2, "b"],
  ["empty", "", 0, 0, ""],
  ["whole", "abc", 0, 3, "abc"],
  ["empty-range", "abc", 1, 1, ""],
  ["at-end", "abc", 3, 3, ""],
  ["non-ascii", "naïve café", 2, 5, "ïve"],
  ["cjk", "日本語テキスト", 3, 7, "テキスト"],
  ["astral", "a\u{1F642}b\u{1F643}c", 1, 4, "\u{1F642}b\u{1F643}"],
  ["astral-only", "\u{1F642}\u{1F643}", 1, 2, "\u{1F643}"],
  ["combining", "e\u0301t\u00e9", 0, 1, "e"],
  ["combining-mark", "e\u0301t\u00e9", 1, 3, "\u0301t"],
];

for (const [name, s, start, end, want] of cases) {
  test(name, () => {
    assert.equal(substring(s, start, end), want);
  });
}
substring.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

// Package substring gets a substring by code point indexes.
package substring

// Substring returns the code points of s from index start up to, not
// including, end.
func Substring(s string, start, end int) string {
	// s[i:j] takes byte indexes, so the code finds the byte index of each
	// code point index.
	return s[offset(s, start):offset(s, end)]
}

// offset returns the byte index of code point k, or len(s) for the end.
func offset(s string, k int) int {
	n := 0
	for i := range s {
		if n == k {
			return i
		}
		n++
	}
	return len(s)
}
substring_test.go 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

package substring

import "testing"

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
func TestSubstring(t *testing.T) {
	cases := []struct {
		name       string
		s          string
		start, end int
		want       string
	}{
		{"middle", "Hello, world", 7, 12, "world"},
		{"prefix", "Hello, world", 0, 5, "Hello"},
		{"one-char", "abc", 1, 2, "b"},
		{"empty", "", 0, 0, ""},
		{"whole", "abc", 0, 3, "abc"},
		{"empty-range", "abc", 1, 1, ""},
		{"at-end", "abc", 3, 3, ""},
		{"non-ascii", "naïve café", 2, 5, "ïve"},
		{"cjk", "日本語テキスト", 3, 7, "テキスト"},
		{"astral", "a\U0001F642b\U0001F643c", 1, 4, "\U0001F642b\U0001F643"},
		{"astral-only", "\U0001F642\U0001F643", 1, 2, "\U0001F643"},
		{"combining", "e\u0301t\u00e9", 0, 1, "e"},
		{"combining-mark", "e\u0301t\u00e9", 1, 3, "\u0301t"},
	}
	for _, c := range cases {
		if got := Substring(c.s, c.start, c.end); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
substring.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

/// Returns the code points of s from index start up to, not including, end.
pub fn substring(s: &str, start: usize, end: usize) -> String {
    // &s[i..j] takes byte indexes and panics inside a character, so the code
    // finds the byte index of each code point index.
    s[offset(s, start)..offset(s, end)].to_string()
}

// offset returns the byte index of code point k, or s.len() for the end.
fn offset(s: &str, k: usize) -> usize {
    s.char_indices().nth(k).map_or(s.len(), |(i, _)| i)
}
tests/substring_test.rs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-substring/.

use algo_get_a_substring::substring;

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
#[test]
fn cases() {
    let cases = [
        ("middle", "Hello, world", 7, 12, "world"),
        ("prefix", "Hello, world", 0, 5, "Hello"),
        ("one-char", "abc", 1, 2, "b"),
        ("empty", "", 0, 0, ""),
        ("whole", "abc", 0, 3, "abc"),
        ("empty-range", "abc", 1, 1, ""),
        ("at-end", "abc", 3, 3, ""),
        ("non-ascii", "naïve café", 2, 5, "ïve"),
        ("cjk", "日本語テキスト", 3, 7, "テキスト"),
        ("astral", "a\u{1F642}b\u{1F643}c", 1, 4, "\u{1F642}b\u{1F643}"),
        ("astral-only", "\u{1F642}\u{1F643}", 1, 2, "\u{1F643}"),
        ("combining", "e\u{301}t\u{e9}", 0, 1, "e"),
        ("combining-mark", "e\u{301}t\u{e9}", 1, 3, "\u{301}t"),
    ];
    for (name, s, start, end, want) in cases {
        assert_eq!(substring(s, start, end), want, "{name}");
    }
}
substring.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-substring/.

# substring S START END: prints the code points of S from index START up to,
# not including, END. ${s:offset:length} counts characters of the locale, so
# the expansion runs in a subshell with the locale C.UTF-8, where each code
# point is one character.
substring() {
  (
    LC_ALL=C.UTF-8
    printf '%s' "${1:$2:$(($3 - $2))}"
  )
}
test_substring.bats 31 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-substring/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/substring.sh"
}

check() { # check WANT S START END
  run substring "$2" "$3" "$4"
  [ "$status" -eq 0 ]
  [ "$output" = "$1" ]
}

@test "middle" { check 'world' 'Hello, world' 7 12; }
@test "prefix" { check 'Hello' 'Hello, world' 0 5; }
@test "one-char" { check 'b' 'abc' 1 2; }
@test "empty" { check '' '' 0 0; }
@test "whole" { check 'abc' 'abc' 0 3; }
@test "empty-range" { check '' 'abc' 1 1; }
@test "at-end" { check '' 'abc' 3 3; }
# C3 AF is U+00EF, and C3 A9 is U+00E9.
@test "non-ascii" { check $'\xc3\xafve' $'na\xc3\xafve caf\xc3\xa9' 2 5; }
@test "cjk" { check 'テキスト' '日本語テキスト' 3 7; }
@test "astral" { check '🙂b🙃' 'a🙂b🙃c' 1 4; }
@test "astral-only" { check '🙃' '🙂🙃' 1 2; }
# CC 81 is U+0301 COMBINING ACUTE ACCENT.
@test "combining" { check 'e' $'e\xcc\x81t\xc3\xa9' 0 1; }
@test "combining-mark" { check $'\xcc\x81t' $'e\xcc\x81t\xc3\xa9' 1 3; }

References

  1. The Python Standard Library, Built-in Types, Common Sequence Operations, note 4; Text Sequence Type
  2. MDN Web Docs, String, UTF-16 characters, Unicode code points, and grapheme clusters
  3. Java SE 25 API, java.lang.String, substring(int, int); offsetByCodePoints
  4. .NET API reference, Char struct
  5. .NET API reference, String.Substring method, Substring(Int32, Int32)
  6. The Go Programming Language Specification, Slice expressions; For statements with range clause
  7. The Rust Standard Library, primitive type str, get; is_char_boundary; char_indices
  8. RFC 3629, UTF-8, a transformation format of ISO 10646, Section 3
  9. Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Shell Parameter Expansion
  10. MDN Web Docs, String.prototype.slice(), Description
  11. MDN Web Docs, String.prototype.substring(), Description
  12. cppreference.com, strncpy, strncpy_s
  13. cppreference.com, std::basic_string substr

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source