Programming Search⌘K

Taskintro

Check whether a string starts with a prefix

Also called starts with, ends with, startswith, endswith, has prefix, has suffix, strip a prefix, remove a suffix.

Check whether a string starts with a prefix or ends with a suffix, remove a prefix or a suffix exactly once, and make the test case-insensitive without a culture-sensitive surprise.

Task

Check whether a string starts with a prefix. The function starts_with(s, prefix) returns true if the first code points of s are the code points of prefix, in order, and ends_with(s, suffix) does the same test at the end of s. For example, starts_with("Hello, world", "Hello") is true, and ends_with("report.txt", ".csv") is false.

The test is case-sensitive, and it compares code points, not the letters that a reader sees. The empty string is a prefix and a suffix of each string, and a prefix that is longer than s does not match.

Solutions

Language Starts with Ends with Remove a prefix
Python s.startswith(p) s.endswith(p) s.removeprefix(p)
JavaScript, TypeScript s.startsWith(p) s.endsWith(p) s.slice(p.length) after the test
Java s.startsWith(p) s.endsWith(p) s.substring(p.length()) after the test
C# s.StartsWith(p, StringComparison.Ordinal) s.EndsWith(p, StringComparison.Ordinal) s[p.Length..] after the test
Go strings.HasPrefix(s, p) strings.HasSuffix(s, p) strings.TrimPrefix(s, p) or strings.CutPrefix(s, p)
Rust s.starts_with(p) s.ends_with(p) s.strip_prefix(p)
C strncmp(s, p, strlen(p)) == 0 memcmp at the end s + strlen(p) after the test
C++ s.starts_with(p) s.ends_with(p) s.substr(p.size()) after the test
Bash [[ $s == "$p"* ]] [[ $s == *"$p" ]] ${s#"$p"}
  • Python. startswith returns "True if string starts with the prefix, otherwise return False"1. "prefix can also be a tuple of prefixes to look for"1, so one call can test more than one prefix.
  • JavaScript and TypeScript. startsWith returns "true if the given characters are found at the beginning of the string, including when searchString is an empty string"2. endsWith has a second argument, endPosition, that "Defaults to str.length"3.
  • Java. startsWith returns true "if the character sequence represented by the argument is a prefix of the character sequence represented by this string"4. "Note also that true will be returned if the argument is an empty string"4.
  • C#. StartsWith(String) "performs a word (case-sensitive and culture-sensitive) comparison using the current culture"5, so the code passes StringComparison.Ordinal. The .NET guide says "Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance"6.
  • Go. "HasPrefix reports whether the string s begins with prefix"7. HasSuffix is the test at the end.
  • Rust. starts_with "Returns true if the given pattern matches a prefix of this string slice"8. The pattern can be a &str, a char or a closure.
  • C. strncmp "Compares at most count characters of two possibly null-terminated arrays"9. With the length of the prefix as the count, the result is 0 only when s starts with the prefix. A shorter s stops at its null character, so the comparison does not read past its end. For the suffix, the code compares the lengths first and then uses memcmp on the last bytes.
  • C++. std::string_view::starts_with (C++20) "Checks if the string view begins with the given prefix"10. ends_with does the test at the end. Both also take a single character.
  • Bash. With == in [[, "the string to the right of the operator is considered a pattern"11. "If you quote any part of the pattern, using any of the shell’s quoting mechanisms, the quoted portion is matched literally"11, so the function quotes the prefix and leaves the * outside the quotes. The function gives the result as the exit status.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of ends_with are in cases/ends.jsonl.

  • empty-prefix, empty-s and both-empty: the empty prefix matches each string, also the empty string. A non-empty prefix does not match the empty string.
  • longer-prefix and ends-longer: a prefix or a suffix that is longer than s does not match. In C, the suffix test must check the lengths before it moves the pointer.
  • case-sensitive and ends-case: Hello does not start with hello, and A.TXT does not end with .txt.
  • non-ascii, cjk and astral: the test compares whole code points, so the byte length or the code unit length of a character has no effect on the result.
  • combining and precomposed: cafe\u0301 starts with cafe, because the accent U+0301 is a separate code point after the e. caf\u00e9 with the precomposed é does not start with cafe. In the same way, cafe\u0301 does not end with e.

Pitfalls

  • Python lstrip and rstrip remove characters, not a prefix. "The chars argument is not a prefix; rather, all combinations of its values are stripped"1. So 'report.txt'.rstrip('.txt') gives repor. Use removeprefix and removesuffix, which remove the text once. For a case-insensitive test, change the case of s first:
name = "report.txt"
print(name.rstrip(".txt"))
print(name.removesuffix(".txt"))
print("Arthur: three!".lstrip("Arthur: "))
print("Arthur: three!".removeprefix("Arthur: "))
print("photo.JPG".lower().endswith((".jpg", ".png")))
Output
repor
report
ee!
three!
True
  • JavaScript startsWith does not take a regex. It throws a TypeError when the argument "is a regex"2. "This method is case-sensitive"2, so change the case of both strings for a case-insensitive test. The second argument gives the index where the test starts:
const s = "Hello, world";
console.log(s.startsWith("world", 7));
console.log(s.toLowerCase().startsWith("hello"));
try {
  s.startsWith(/Hello/);
} catch (e) {
  console.log(e.name);
}
Output
true
true
TypeError
  • Java has no case-insensitive startsWith. Use regionMatches(true, 0, prefix, 0, prefix.length()). It "Tests if two string regions are equal"4, and the first argument turns off the case test:
public class Main {
  public static void main(String[] args) {
    String s = "Hello, world";
    System.out.println(s.startsWith("hello"));
    System.out.println(s.regionMatches(true, 0, "hello", 0, 5));
    System.out.println(s.startsWith("world", 7));
  }
}
Output
false
true
true
  • C# StartsWith(String) uses the current culture. The culture rules can ignore some characters and can compare a letter and its accent as one unit. So cafe\u0301 does not start with cafe, and a string that starts with a soft hyphen (U+00AD) starts with cafe. With StringComparison.Ordinal, the results are the opposite. Use OrdinalIgnoreCase for a case-insensitive test:
using System;
using System.Globalization;

CultureInfo.CurrentCulture = new CultureInfo("en-US");
string s = "cafe\u0301";
Console.WriteLine(s.StartsWith("cafe"));
Console.WriteLine(s.StartsWith("cafe", StringComparison.Ordinal));
Console.WriteLine("\u00ADcafe".StartsWith("cafe"));
Console.WriteLine("Hello".StartsWith("hello", StringComparison.OrdinalIgnoreCase));
Output
False
True
True
True
  • Go TrimLeft is not TrimPrefix. TrimLeft removes "all leading Unicode code points contained in cutset"7, so a TrimLeft of a from aaab gives b. TrimPrefix removes the prefix once. CutPrefix also "reports whether it found the prefix"7:
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimLeft("aaab", "a"))
	fmt.Println(strings.TrimPrefix("aaab", "a"))
	after, found := strings.CutPrefix("key=value", "key=")
	fmt.Println(after, found)
}
Output
b
aab
value true
  • Rust strip_prefix returns an Option. "Unlike trim_start_matches, this method removes the prefix exactly once"8, and it returns None when there is no prefix. A closure as the pattern tests the first character:
fn main() {
    println!("{:?}", "aaab".strip_prefix('a'));
    println!("{:?}", "aaab".trim_start_matches('a'));
    println!("{:?}", "b".strip_prefix('a'));
    println!("{}", "42 apples".starts_with(|c: char| c.is_ascii_digit()));
}
Output
Some("aab")
"b"
None
true
  • C strncmp with the wrong count. If the count is the length of s, a short s such as ab seems to start with abc, because only two characters are compared. Use the length of the prefix:
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "ab";
    const char *prefix = "abc";
    // Wrong: the count is the length of s, so only "ab" is compared.
    printf("%d\n", strncmp(s, prefix, strlen(s)) == 0);
    // Right: the count is the length of the prefix.
    printf("%d\n", strncmp(s, prefix, strlen(prefix)) == 0);
    return 0;
}
Output
1
0
  • C++ before C++20 has no starts_with. s.rfind(p, 0) == 0 tests only the position 0. s.find(p) == 0 gives the correct result, but it searches all of s when the prefix is not at the start:
#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, world";
    // Before C++20: rfind with the position 0 looks only at the start.
    std::cout << (s.rfind("Hello", 0) == 0) << "\n";
    std::cout << s.starts_with("Hello") << " " << s.ends_with('d') << "\n";
    // find searches all of s, so it is slow when there is no match at 0.
    std::cout << (s.find("world") == 0) << "\n";
}
Output
1
1 1
0
  • Bash reads an unquoted prefix as a pattern. If the prefix is * and it has no quotes, each string matches. With the option nocasematch, "the match is performed without regard to the case of alphabetic characters"11:
p='*'
s='Hello'
[[ $s == $p* ]] && echo "unquoted: match"
[[ $s == "$p"* ]] || echo "quoted: no match"
shopt -s nocasematch
[[ $s == "hello"* ]] && echo "nocasematch: match"
Output
unquoted: match
quoted: no match
nocasematch: match

Code

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

prefix.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.


def starts_with(s: str, prefix: str) -> bool:
    """Return True if s starts with prefix."""
    return s.startswith(prefix)


def ends_with(s: str, suffix: str) -> bool:
    """Return True if s ends with suffix."""
    return s.endswith(suffix)
test_prefix.py 45 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

import pytest

from prefix import ends_with, starts_with

# U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
STARTS = {
    "yes": ("Hello, world", "Hello", True),
    "no": ("Hello, world", "world", False),
    "whole": ("abc", "abc", True),
    "empty-prefix": ("abc", "", True),
    "empty-s": ("", "a", False),
    "both-empty": ("", "", True),
    "longer-prefix": ("ab", "abc", False),
    "case-sensitive": ("Hello", "hello", False),
    "non-ascii": ("caf\u00e9 au lait", "caf\u00e9", True),
    "cjk": ("日本語", "日本", True),
    "astral": ("\U0001f642\U0001f643", "\U0001f642", True),
    "astral-no": ("\U0001f642", "\U0001f643", False),
    "combining": ("cafe\u0301", "cafe", True),
    "precomposed": ("caf\u00e9", "cafe", False),
}
ENDS = {
    "ends-yes": ("report.txt", ".txt", True),
    "ends-no": ("report.txt", ".csv", False),
    "ends-empty": ("abc", "", True),
    "ends-longer": ("txt", "a.txt", False),
    "ends-case": ("A.TXT", ".txt", False),
    "ends-astral": ("a\U0001f642", "\U0001f642", True),
    "ends-combining": ("cafe\u0301", "e", False),
}


@pytest.mark.parametrize("name", STARTS)
def test_starts_with(name):
    s, prefix, want = STARTS[name]
    assert starts_with(s, prefix) is want


@pytest.mark.parametrize("name", ENDS)
def test_ends_with(name):
    s, suffix, want = ENDS[name]
    assert ends_with(s, suffix) is want
prefix.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

#include "prefix.hpp"

bool starts_with(std::string_view s, std::string_view prefix) {
    return s.starts_with(prefix);
}

bool ends_with(std::string_view s, std::string_view suffix) {
    return s.ends_with(suffix);
}
prefix.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

#ifndef PREFIX_HPP
#define PREFIX_HPP

#include <string_view>

// starts_with reports whether the UTF-8 string s starts with prefix.
bool starts_with(std::string_view s, std::string_view prefix);

// ends_with reports whether the UTF-8 string s ends with suffix.
bool ends_with(std::string_view s, std::string_view suffix);

#endif
test_prefix.cpp 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

#include "prefix.hpp"

#include <string_view>
#include <iostream>

static int failures = 0;

static void check(std::string_view name, bool got, bool want) {
    if (got != want) {
        std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
        failures++;
    }
}

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
int main() {
    check("yes", starts_with("Hello, world", "Hello"), true);
    check("no", starts_with("Hello, world", "world"), false);
    check("whole", starts_with("abc", "abc"), true);
    check("empty-prefix", starts_with("abc", ""), true);
    check("empty-s", starts_with("", "a"), false);
    check("both-empty", starts_with("", ""), true);
    check("longer-prefix", starts_with("ab", "abc"), false);
    check("case-sensitive", starts_with("Hello", "hello"), false);
    check("non-ascii", starts_with("caf\xc3\xa9 au lait", "caf\xc3\xa9"), true);
    check("cjk", starts_with("日本語", "日本"), true);
    check("astral", starts_with("\xf0\x9f\x99\x82\xf0\x9f\x99\x83", "\xf0\x9f\x99\x82"), true);
    check("astral-no", starts_with("\xf0\x9f\x99\x82", "\xf0\x9f\x99\x83"), false);
    check("combining", starts_with("cafe\xcc\x81", "cafe"), true);
    check("precomposed", starts_with("caf\xc3\xa9", "cafe"), false);
    check("ends-yes", ends_with("report.txt", ".txt"), true);
    check("ends-no", ends_with("report.txt", ".csv"), false);
    check("ends-empty", ends_with("abc", ""), true);
    check("ends-longer", ends_with("txt", "a.txt"), false);
    check("ends-case", ends_with("A.TXT", ".txt"), false);
    check("ends-astral", ends_with("a\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82"), true);
    check("ends-combining", ends_with("cafe\xcc\x81", "e"), false);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Prefix.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

/** Checks whether a string starts or ends with another string. */
public final class Prefix {
  private Prefix() {}

  /** Returns true if s starts with prefix. */
  public static boolean startsWith(String s, String prefix) {
    return s.startsWith(prefix);
  }

  /** Returns true if s ends with suffix. */
  public static boolean endsWith(String s, String suffix) {
    return s.endsWith(suffix);
  }
}
PrefixTest.java 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

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 PrefixTest {
  // U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
  static Stream<Arguments> starts() {
    return Stream.of(
        Arguments.of("yes", "Hello, world", "Hello", true),
        Arguments.of("no", "Hello, world", "world", false),
        Arguments.of("whole", "abc", "abc", true),
        Arguments.of("empty-prefix", "abc", "", true),
        Arguments.of("empty-s", "", "a", false),
        Arguments.of("both-empty", "", "", true),
        Arguments.of("longer-prefix", "ab", "abc", false),
        Arguments.of("case-sensitive", "Hello", "hello", false),
        Arguments.of("non-ascii", "caf\u00e9 au lait", "caf\u00e9", true),
        Arguments.of("cjk", "日本語", "日本", true),
        Arguments.of("astral", "\ud83d\ude42\ud83d\ude43", "\ud83d\ude42", true),
        Arguments.of("astral-no", "\ud83d\ude42", "\ud83d\ude43", false),
        Arguments.of("combining", "cafe\u0301", "cafe", true),
        Arguments.of("precomposed", "caf\u00e9", "cafe", false));
  }

  static Stream<Arguments> ends() {
    return Stream.of(
        Arguments.of("ends-yes", "report.txt", ".txt", true),
        Arguments.of("ends-no", "report.txt", ".csv", false),
        Arguments.of("ends-empty", "abc", "", true),
        Arguments.of("ends-longer", "txt", "a.txt", false),
        Arguments.of("ends-case", "A.TXT", ".txt", false),
        Arguments.of("ends-astral", "a\ud83d\ude42", "\ud83d\ude42", true),
        Arguments.of("ends-combining", "cafe\u0301", "e", false));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("starts")
  void startsWith(String name, String s, String prefix, boolean want) {
    assertEquals(want, Prefix.startsWith(s, prefix));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("ends")
  void endsWith(String name, String s, String suffix, boolean want) {
    assertEquals(want, Prefix.endsWith(s, suffix));
  }
}
prefix.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

#include "prefix.h"

#include <string.h>

bool starts_with(const char *s, const char *prefix) {
    return strncmp(s, prefix, strlen(prefix)) == 0;
}

bool ends_with(const char *s, const char *suffix) {
    size_t n = strlen(s);
    size_t m = strlen(suffix);
    // A suffix longer than s cannot match, and the check keeps s + n - m in s.
    return m <= n && memcmp(s + n - m, suffix, m) == 0;
}
prefix.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

#ifndef PREFIX_H
#define PREFIX_H

#include <stdbool.h>

// starts_with reports whether the UTF-8 string s starts with prefix.
bool starts_with(const char *s, const char *prefix);

// ends_with reports whether the UTF-8 string s ends with suffix.
bool ends_with(const char *s, const char *suffix);

#endif
test_prefix.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

#include "prefix.h"

#include <stdbool.h>
#include <stdio.h>

static int failures = 0;

static void check(const char *name, bool got, bool want) {
    if (got != want) {
        fprintf(stderr, "case %s: got %d, want %d\n", name, got, want);
        failures++;
    }
}

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
int main(void) {
    check("yes", starts_with("Hello, world", "Hello"), true);
    check("no", starts_with("Hello, world", "world"), false);
    check("whole", starts_with("abc", "abc"), true);
    check("empty-prefix", starts_with("abc", ""), true);
    check("empty-s", starts_with("", "a"), false);
    check("both-empty", starts_with("", ""), true);
    check("longer-prefix", starts_with("ab", "abc"), false);
    check("case-sensitive", starts_with("Hello", "hello"), false);
    check("non-ascii", starts_with("caf\xc3\xa9 au lait", "caf\xc3\xa9"), true);
    check("cjk", starts_with("日本語", "日本"), true);
    check("astral", starts_with("\xf0\x9f\x99\x82\xf0\x9f\x99\x83", "\xf0\x9f\x99\x82"), true);
    check("astral-no", starts_with("\xf0\x9f\x99\x82", "\xf0\x9f\x99\x83"), false);
    check("combining", starts_with("cafe\xcc\x81", "cafe"), true);
    check("precomposed", starts_with("caf\xc3\xa9", "cafe"), false);
    check("ends-yes", ends_with("report.txt", ".txt"), true);
    check("ends-no", ends_with("report.txt", ".csv"), false);
    check("ends-empty", ends_with("abc", ""), true);
    check("ends-longer", ends_with("txt", "a.txt"), false);
    check("ends-case", ends_with("A.TXT", ".txt"), false);
    check("ends-astral", ends_with("a\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82"), true);
    check("ends-combining", ends_with("cafe\xcc\x81", "e"), false);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Prefix.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

using System;

/// <summary>Checks whether a string starts or ends with another string.</summary>
public static class Prefix
{
    // StartsWith(string) without a StringComparison uses the rules of the
    // current culture, so the code gives Ordinal to compare the code units.
    public static bool StartsWith(string s, string prefix) =>
        s.StartsWith(prefix, StringComparison.Ordinal);

    public static bool EndsWith(string s, string suffix) =>
        s.EndsWith(suffix, StringComparison.Ordinal);
}
PrefixTests.cs 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

using Xunit;

public sealed class PrefixTests
{
    // U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
    public static TheoryData<string, string, string, bool> Starts => new()
    {
        { "yes", "Hello, world", "Hello", true },
        { "no", "Hello, world", "world", false },
        { "whole", "abc", "abc", true },
        { "empty-prefix", "abc", "", true },
        { "empty-s", "", "a", false },
        { "both-empty", "", "", true },
        { "longer-prefix", "ab", "abc", false },
        { "case-sensitive", "Hello", "hello", false },
        { "non-ascii", "caf\u00e9 au lait", "caf\u00e9", true },
        { "cjk", "日本語", "日本", true },
        { "astral", "\U0001f642\U0001f643", "\U0001f642", true },
        { "astral-no", "\U0001f642", "\U0001f643", false },
        { "combining", "cafe\u0301", "cafe", true },
        { "precomposed", "caf\u00e9", "cafe", false },
    };

    public static TheoryData<string, string, string, bool> Ends => new()
    {
        { "ends-yes", "report.txt", ".txt", true },
        { "ends-no", "report.txt", ".csv", false },
        { "ends-empty", "abc", "", true },
        { "ends-longer", "txt", "a.txt", false },
        { "ends-case", "A.TXT", ".txt", false },
        { "ends-astral", "a\U0001f642", "\U0001f642", true },
        { "ends-combining", "cafe\u0301", "e", false },
    };

    [Theory]
    [MemberData(nameof(Starts))]
    public void StartsWith(string name, string s, string prefix, bool want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Prefix.StartsWith(s, prefix));
    }

    [Theory]
    [MemberData(nameof(Ends))]
    public void EndsWith(string name, string s, string suffix, bool want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Prefix.EndsWith(s, suffix));
    }
}
prefix.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

// startsWith reports whether s starts with prefix.
export function startsWith(s, prefix) {
  return s.startsWith(prefix);
}

// endsWith reports whether s ends with suffix.
export function endsWith(s, suffix) {
  return s.endsWith(suffix);
}
prefix.test.js 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

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

import { endsWith, startsWith } from "./prefix.js";

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const starts = [
  ["yes", "Hello, world", "Hello", true],
  ["no", "Hello, world", "world", false],
  ["whole", "abc", "abc", true],
  ["empty-prefix", "abc", "", true],
  ["empty-s", "", "a", false],
  ["both-empty", "", "", true],
  ["longer-prefix", "ab", "abc", false],
  ["case-sensitive", "Hello", "hello", false],
  ["non-ascii", "caf\u00e9 au lait", "caf\u00e9", true],
  ["cjk", "日本語", "日本", true],
  ["astral", "\u{1f642}\u{1f643}", "\u{1f642}", true],
  ["astral-no", "\u{1f642}", "\u{1f643}", false],
  ["combining", "cafe\u0301", "cafe", true],
  ["precomposed", "caf\u00e9", "cafe", false],
];
const ends = [
  ["ends-yes", "report.txt", ".txt", true],
  ["ends-no", "report.txt", ".csv", false],
  ["ends-empty", "abc", "", true],
  ["ends-longer", "txt", "a.txt", false],
  ["ends-case", "A.TXT", ".txt", false],
  ["ends-astral", "a\u{1f642}", "\u{1f642}", true],
  ["ends-combining", "cafe\u0301", "e", false],
];

for (const [name, s, prefix, want] of starts) {
  test(name, () => {
    assert.equal(startsWith(s, prefix), want);
  });
}
for (const [name, s, suffix, want] of ends) {
  test(name, () => {
    assert.equal(endsWith(s, suffix), want);
  });
}
prefix.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

// startsWith reports whether s starts with prefix.
export function startsWith(s: string, prefix: string): boolean {
  return s.startsWith(prefix);
}

// endsWith reports whether s ends with suffix.
export function endsWith(s: string, suffix: string): boolean {
  return s.endsWith(suffix);
}
prefix.test.ts 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

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

import { endsWith, startsWith } from "./prefix.ts";

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const starts = [
  ["yes", "Hello, world", "Hello", true],
  ["no", "Hello, world", "world", false],
  ["whole", "abc", "abc", true],
  ["empty-prefix", "abc", "", true],
  ["empty-s", "", "a", false],
  ["both-empty", "", "", true],
  ["longer-prefix", "ab", "abc", false],
  ["case-sensitive", "Hello", "hello", false],
  ["non-ascii", "caf\u00e9 au lait", "caf\u00e9", true],
  ["cjk", "日本語", "日本", true],
  ["astral", "\u{1f642}\u{1f643}", "\u{1f642}", true],
  ["astral-no", "\u{1f642}", "\u{1f643}", false],
  ["combining", "cafe\u0301", "cafe", true],
  ["precomposed", "caf\u00e9", "cafe", false],
];
const ends = [
  ["ends-yes", "report.txt", ".txt", true],
  ["ends-no", "report.txt", ".csv", false],
  ["ends-empty", "abc", "", true],
  ["ends-longer", "txt", "a.txt", false],
  ["ends-case", "A.TXT", ".txt", false],
  ["ends-astral", "a\u{1f642}", "\u{1f642}", true],
  ["ends-combining", "cafe\u0301", "e", false],
];

for (const [name, s, prefix, want] of starts) {
  test(name, () => {
    assert.equal(startsWith(s, prefix), want);
  });
}
for (const [name, s, suffix, want] of ends) {
  test(name, () => {
    assert.equal(endsWith(s, suffix), want);
  });
}
prefix.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

// Package prefix checks whether a string starts or ends with another string.
package prefix

import "strings"

// StartsWith reports whether s starts with prefix.
func StartsWith(s, prefix string) bool {
	return strings.HasPrefix(s, prefix)
}

// EndsWith reports whether s ends with suffix.
func EndsWith(s, suffix string) bool {
	return strings.HasSuffix(s, suffix)
}
prefix_test.go 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

package prefix

import "testing"

type prefixCase struct {
	name, s, p string
	want       bool
}

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
var starts = []prefixCase{
	{"yes", "Hello, world", "Hello", true},
	{"no", "Hello, world", "world", false},
	{"whole", "abc", "abc", true},
	{"empty-prefix", "abc", "", true},
	{"empty-s", "", "a", false},
	{"both-empty", "", "", true},
	{"longer-prefix", "ab", "abc", false},
	{"case-sensitive", "Hello", "hello", false},
	{"non-ascii", "caf\u00e9 au lait", "caf\u00e9", true},
	{"cjk", "日本語", "日本", true},
	{"astral", "\U0001f642\U0001f643", "\U0001f642", true},
	{"astral-no", "\U0001f642", "\U0001f643", false},
	{"combining", "cafe\u0301", "cafe", true},
	{"precomposed", "caf\u00e9", "cafe", false},
}

var ends = []prefixCase{
	{"ends-yes", "report.txt", ".txt", true},
	{"ends-no", "report.txt", ".csv", false},
	{"ends-empty", "abc", "", true},
	{"ends-longer", "txt", "a.txt", false},
	{"ends-case", "A.TXT", ".txt", false},
	{"ends-astral", "a\U0001f642", "\U0001f642", true},
	{"ends-combining", "cafe\u0301", "e", false},
}

func TestStartsWith(t *testing.T) {
	for _, c := range starts {
		if got := StartsWith(c.s, c.p); got != c.want {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestEndsWith(t *testing.T) {
	for _, c := range ends {
		if got := EndsWith(c.s, c.p); got != c.want {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
prefix.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

/// Returns true if s starts with prefix.
pub fn starts_with(s: &str, prefix: &str) -> bool {
    s.starts_with(prefix)
}

/// Returns true if s ends with suffix.
pub fn ends_with(s: &str, suffix: &str) -> bool {
    s.ends_with(suffix)
}
tests/prefix_test.rs 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

use algo_check_whether_a_string_starts_with_a_prefix::{ends_with, starts_with};

// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
#[test]
fn starts() {
    let cases = [
        ("yes", "Hello, world", "Hello", true),
        ("no", "Hello, world", "world", false),
        ("whole", "abc", "abc", true),
        ("empty-prefix", "abc", "", true),
        ("empty-s", "", "a", false),
        ("both-empty", "", "", true),
        ("longer-prefix", "ab", "abc", false),
        ("case-sensitive", "Hello", "hello", false),
        ("non-ascii", "caf\u{e9} au lait", "caf\u{e9}", true),
        ("cjk", "日本語", "日本", true),
        ("astral", "\u{1f642}\u{1f643}", "\u{1f642}", true),
        ("astral-no", "\u{1f642}", "\u{1f643}", false),
        ("combining", "cafe\u{301}", "cafe", true),
        ("precomposed", "caf\u{e9}", "cafe", false),
    ];
    for (name, s, prefix, want) in cases {
        assert_eq!(starts_with(s, prefix), want, "{name}");
    }
}

#[test]
fn ends() {
    let cases = [
        ("ends-yes", "report.txt", ".txt", true),
        ("ends-no", "report.txt", ".csv", false),
        ("ends-empty", "abc", "", true),
        ("ends-longer", "txt", "a.txt", false),
        ("ends-case", "A.TXT", ".txt", false),
        ("ends-astral", "a\u{1f642}", "\u{1f642}", true),
        ("ends-combining", "cafe\u{301}", "e", false),
    ];
    for (name, s, suffix, want) in cases {
        assert_eq!(ends_with(s, suffix), want, "{name}");
    }
}
prefix.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

# starts_with S PREFIX: exits with status 0 if S starts with PREFIX. The quotes
# around "$2" make PREFIX a literal string, and the * outside them matches the
# rest of S.
starts_with() {
  [[ $1 == "$2"* ]]
}

# ends_with S SUFFIX: exits with status 0 if S ends with SUFFIX.
ends_with() {
  [[ $1 == *"$2" ]]
}
test_prefix.bats 37 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-starts-with-a-prefix/.

bats_require_minimum_version 1.5.0

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

check() { # check STATUS FUNCTION S AFFIX
  run "$2" "$3" "$4"
  [ "$status" -eq "$1" ]
  [ "$output" = "" ]
}

# CC 81 is U+0301 COMBINING ACUTE ACCENT, and C3 A9 is U+00E9.
@test "yes" { check 0 starts_with 'Hello, world' 'Hello'; }
@test "no" { check 1 starts_with 'Hello, world' 'world'; }
@test "whole" { check 0 starts_with 'abc' 'abc'; }
@test "empty-prefix" { check 0 starts_with 'abc' ''; }
@test "empty-s" { check 1 starts_with '' 'a'; }
@test "both-empty" { check 0 starts_with '' ''; }
@test "longer-prefix" { check 1 starts_with 'ab' 'abc'; }
@test "case-sensitive" { check 1 starts_with 'Hello' 'hello'; }
@test "non-ascii" { check 0 starts_with $'caf\xc3\xa9 au lait' $'caf\xc3\xa9'; }
@test "cjk" { check 0 starts_with '日本語' '日本'; }
@test "astral" { check 0 starts_with $'\xf0\x9f\x99\x82\xf0\x9f\x99\x83' $'\xf0\x9f\x99\x82'; }
@test "astral-no" { check 1 starts_with $'\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x83'; }
@test "combining" { check 0 starts_with $'cafe\xcc\x81' 'cafe'; }
@test "precomposed" { check 1 starts_with $'caf\xc3\xa9' 'cafe'; }
@test "ends-yes" { check 0 ends_with 'report.txt' '.txt'; }
@test "ends-no" { check 1 ends_with 'report.txt' '.csv'; }
@test "ends-empty" { check 0 ends_with 'abc' ''; }
@test "ends-longer" { check 1 ends_with 'txt' 'a.txt'; }
@test "ends-case" { check 1 ends_with 'A.TXT' '.txt'; }
@test "ends-astral" { check 0 ends_with $'a\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x82'; }
@test "ends-combining" { check 1 ends_with $'cafe\xcc\x81' 'e'; }

References

  1. The Python Standard Library, Built-in Types, str.startswith; str.removeprefix; str.lstrip
  2. MDN Web Docs, String.prototype.startsWith(), Return value; Exceptions; Description
  3. MDN Web Docs, String.prototype.endsWith(), Parameters
  4. Java SE 25 API, java.lang.String, startsWith(String); regionMatches(boolean, int, String, int, int)
  5. .NET API reference, String.StartsWith method, StartsWith(String); StartsWith(Char)
  6. .NET documentation, Best practices for comparing strings, Recommendations for string usage
  7. Go standard library, package strings, HasPrefix, CutPrefix, TrimLeft
  8. The Rust Standard Library, primitive type str, starts_with, strip_prefix
  9. cppreference.com, strncmp
  10. cppreference.com, std::basic_string_view starts_with
  11. Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Conditional Constructs

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