Taskintro
Compare strings
Also called string comparison, compare two strings, strcmp, compareTo, string equality, lexicographic order, sort strings, three-way comparison.
Compare two strings for equality and order, and avoid a compare of addresses, of UTF-16 code units or of locale rules when you want the order of the code points.
- Evidence
- Code in 10 languages
Task
Compare two strings. The function compare(a, b) returns -1 if a is before b, 0 if the strings are equal, and 1 if a is after b. The function equals(a, b) returns true if the strings have the same code points in the same order. For example, compare("apple", "banana") is -1, and compare("pear", "apple") is 1.
The order is the order of the code points. At the first position where the strings are different, the string with the smaller code point is first, and a prefix is before the longer string. This order is not the order of a dictionary: Z is before a, and 10 is before 9.
Solutions
| Language | Equal | Order of code points | Order of the library |
|---|---|---|---|
| Python | a == b |
(a > b) - (a < b) |
the same |
| JavaScript, TypeScript | a === b |
a loop with codePointAt |
UTF-16 code units |
| Java | a.equals(b) |
a loop with codePointAt |
UTF-16 code units |
| C# | string.Equals(a, b, StringComparison.Ordinal) |
a loop with char.ConvertToUtf32 |
the current culture |
| Go | a == b |
strings.Compare(a, b) |
the same |
| Rust | a == b |
a.cmp(b) |
the same |
| C | strcmp(a, b) == 0 |
the sign of strcmp(a, b) |
the same |
| C++ | a == b |
the sign of a.compare(b) |
the same |
| Bash | [[ $a == "$b" ]] |
[[ $a < $b ]] with LC_ALL=C |
the current locale |
- Python. "Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters"1. A
boolis anint, so(a > b) - (a < b)is -1, 0 or 1. - JavaScript and TypeScript. The
<operator compares strings "based on the values of the UTF-16 code units (not Unicode code points) they contain"2. A code point above U+FFFF has a high surrogate from U+D800 to U+DBFF as its first code unit, so<puts it before U+E000 to U+FFFF. The loop compares code points, and it moves 2 code units for a code point above U+FFFF. - Java.
compareTocomparescharvalues, which are UTF-16 code units, so the code uses the same loop as JavaScript.equalscompares the characters of two strings. - C#.
string.Compare"uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters"3.CompareOrdinalcompares UTF-16 code units, so the code uses a loop over the code points. - Go. "The result will be 0 if a == b, -1 if a < b, and +1 if a > b"4. Go compares the bytes of the strings, and the order of UTF-8 bytes is the order of the code points.
- Rust. "Strings are ordered lexicographically by their byte values"5.
cmpreturns anOrdering, and the code changes it to -1, 0 or 1. - C. "The sign of the result is the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the strings being compared"6. The code keeps only the sign.
- C++.
std::stringcompares withTraits::compare, which forcharcompares the characters asunsigned char.comparereturns a negative number, 0 or a positive number, and the code keeps the sign. - Bash. "When used with [[, the ‘<’ and ‘>’ operators sort lexicographically using the current locale"7. With
LC_ALL=C, the locale is the C locale, and the order is the order of the bytes. The function sets it in a subshell.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of equals are in cases/equal.jsonl.
both-emptyandempty-first: two empty strings are equal, and the empty string is before each other string.prefixandprefix-longer:appis beforeapple, because it is a prefix of it.upper-before-lowerandlower-after-upper: the code point ofZis U+005A and the code point ofais U+0061, soZebrais beforeapple.digits:10is before9, because1is before9. Compare numbers as numbers.non-ascii:éis U+00E9, so it is afterz, which is U+007A.astral-after-bmpandastral: U+FF61 is before U+1F642 in code point order. A compare of UTF-16 code units gives the opposite result, so this case fails in JavaScript, Java and C# with the library operator.combiningandeq-combining:caféandcafélook the same, but they have different code points, so they are not equal.eis U+0065 andéis U+00E9, socaféis first.eq-caseandeq-trailing-space: a difference in case or one more space makes the strings different.
Pitfalls
- Python sorts the capital letters first.
sorteduses the order of the code points, soCherryis beforeapple. For a sort with no case, usekey=str.casefold. Casefolding "is intended to remove all case distinctions in a string"8, so it also matchesßandSS:
words = ["banana", "Cherry", "apple"]
print(sorted(words))
print(sorted(words, key=str.casefold))
print("10" < "9", int("10") < int("9"))
print("Straße".casefold() == "STRASSE".casefold())
['Cherry', 'apple', 'banana']
['apple', 'banana', 'Cherry']
True False
True
- JavaScript sort and < use UTF-16 code units. U+FF61 is after an emoji with
<. The defaultsortalso putsBbeforea. For text that people read, uselocaleCompare, which "returns a number indicating whether this string comes before, or after, or is the same as the given string in sort order"9:
const a = "\uff61";
const b = "\u{1f642}";
console.log(a < b);
console.log(["b", "a", "B", "A"].sort());
console.log(["b", "a", "B", "A"].sort((x, y) => x.localeCompare(y, "en")));
console.log("a".localeCompare("B", "en"));
false
[ 'A', 'B', 'a', 'b' ]
[ 'a', 'A', 'b', 'B' ]
-1
- Java == compares references. Two
Stringobjects with the same text are different objects, so==is false. Useequals.compareTodoes not return only -1 and 1: it "returns the difference of the two character values"10:
public class Main {
public static void main(String[] args) {
String a = "apple";
String b = new String("apple");
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println("a".compareTo("c"));
System.out.println("apple".equalsIgnoreCase("APPLE"));
}
}
false
true
-2
true
- C# string.Compare uses the current culture. In the
en-USculture,ais beforeB, but in the ordinal orderBis first. The .NET guide says: "Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance"11. The==operator is an ordinal compare:
using System;
using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine(string.Compare("a", "B"));
Console.WriteLine(Math.Sign(string.CompareOrdinal("a", "B")));
Console.WriteLine(string.Equals("a", "A", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("a" == "a");
-1
1
True
True
- Go strings.Compare is rarely necessary. "It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on"4. Use
Compareas the function ofslices.SortFunc.strings.EqualFoldcompares with no case:
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
fmt.Println("B" < "a", "a" < "b")
fmt.Println(strings.EqualFold("Go", "GO"))
words := []string{"b", "a", "B"}
slices.SortFunc(words, strings.Compare)
fmt.Println(words)
}
true true
true
[B a b]
- Rust sort is not alphabetical. The byte order "is not necessarily the same as “alphabetical” order, which varies by language and locale"5. A sort with
to_lowercaseas the key ignores the case.eq_ignore_ascii_casechanges only the ASCII letters:
fn main() {
let mut words = vec!["banana", "Cherry", "apple"];
words.sort();
println!("{words:?}");
words.sort_by_key(|w| w.to_lowercase());
println!("{words:?}");
println!("{}", "Rust".eq_ignore_ascii_case("RUST"));
}
["Cherry", "apple", "banana"]
["apple", "banana", "Cherry"]
true
- C == compares pointers. Two arrays with the same text have different addresses. Use
strcmp, and use only the sign of its result, because the value can be any negative or positive number:
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "text";
char b[] = "text";
const char *p = a;
const char *q = b;
// p == q compares two addresses, not the characters.
printf("%d\n", p == q);
printf("%d\n", strcmp(a, b) == 0);
int r = strcmp("a", "c");
printf("%d\n", (r > 0) - (r < 0));
return 0;
}
0
1
-1
- C++ compares text only when one side is a std::string. Two
const char *values compare as pointers. When one side is astd::string, "All comparisons are done via the compare() member function"12. In C++20,<=>gives a three-way result:
#include <compare>
#include <iostream>
#include <string>
int main() {
const char *p = "text";
std::string s = "text";
// s == p compares the characters, because one side is a std::string.
std::cout << (s == p) << "\n";
std::cout << (s.compare("texts") < 0) << "\n";
std::cout << ((s <=> std::string("tex")) > 0) << "\n";
}
1
1
1
- Bash [ reads < as a redirection. In
[ $a < $b ], the shell opens the file that$bnames, and[sees only one argument. Write\<in[, or use[[. "The test command uses ASCII ordering"7, and[[uses the order of the locale:
export LC_ALL=C
a='B'
b='a'
[[ $a < $b ]] && echo "[[: B < a"
[ "$a" \< "$b" ] && echo "[: B < a, with \\<"
d=$(mktemp -d)
cd "$d" || exit 1
# Without the backslash, < reads the file a, which does not exist.
{ [ "$a" < "$b" ]; } 2>/dev/null || echo "[ without \\: < is a redirection"
cd / && rmdir "$d"
[[: B < a
[: B < a, with \<
[ without \: < is a redirection
Related tasks
- Change the case of a string: change the case before a compare with no case.
- Check whether a string starts with a prefix: compare only the start or the end of a string.
- Normalize Unicode text: make
caféandcaféequal before a compare.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-strings/.
def compare(a: str, b: str) -> int:
"""Return -1, 0 or 1 for the code point order of a and b."""
# Python compares strings by code points, and True - False is 1.
return (a > b) - (a < b)
def equals(a: str, b: str) -> bool:
"""Return True if a and b have the same code points."""
return a == b
test_compare.py 44 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-strings/.
import pytest
from compare import compare, equals
# U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
COMPARE = {
"less": ("apple", "banana", -1),
"equal": ("apple", "apple", 0),
"greater": ("pear", "apple", 1),
"both-empty": ("", "", 0),
"empty-first": ("", "a", -1),
"prefix": ("app", "apple", -1),
"prefix-longer": ("apple", "app", 1),
"upper-before-lower": ("Zebra", "apple", -1),
"lower-after-upper": ("a", "A", 1),
"digits": ("10", "9", -1),
"non-ascii": ("\u00e9", "z", 1),
"astral-after-bmp": ("\uff61", "\U0001f642", -1),
"astral": ("\U0001f642", "\U0001f643", -1),
"combining": ("cafe\u0301", "caf\u00e9", -1),
}
EQUAL = {
"eq-same": ("abc", "abc", True),
"eq-case": ("abc", "ABC", False),
"eq-empty": ("", "", True),
"eq-combining": ("cafe\u0301", "caf\u00e9", False),
"eq-astral": ("\U0001f642", "\U0001f642", True),
"eq-trailing-space": ("abc", "abc ", False),
}
@pytest.mark.parametrize("name", COMPARE)
def test_compare(name):
a, b, want = COMPARE[name]
assert compare(a, b) == want
@pytest.mark.parametrize("name", EQUAL)
def test_equals(name):
a, b, want = EQUAL[name]
assert equals(a, b) is want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
#include "compare.hpp"
int compare(std::string_view a, std::string_view b) {
// char_traits<char> compares the characters as unsigned char, so the
// order is the order of the UTF-8 bytes.
int r = a.compare(b);
return (r > 0) - (r < 0);
}
bool equals(std::string_view a, std::string_view b) {
return a == b;
}
compare.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
#ifndef COMPARE_HPP
#define COMPARE_HPP
#include <string_view>
// compare returns -1, 0 or 1 for the code point order of the UTF-8 strings a
// and b.
int compare(std::string_view a, std::string_view b);
// equals reports whether a and b have the same bytes.
bool equals(std::string_view a, std::string_view b);
#endif
test_compare.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
#include "compare.hpp"
#include <string_view>
#include <iostream>
static int failures = 0;
static void check(std::string_view name, int got, int want) {
if (got != want) {
std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
failures++;
}
}
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
int main() {
check("less", compare("apple", "banana"), -1);
check("equal", compare("apple", "apple"), 0);
check("greater", compare("pear", "apple"), 1);
check("both-empty", compare("", ""), 0);
check("empty-first", compare("", "a"), -1);
check("prefix", compare("app", "apple"), -1);
check("prefix-longer", compare("apple", "app"), 1);
check("upper-before-lower", compare("Zebra", "apple"), -1);
check("lower-after-upper", compare("a", "A"), 1);
check("digits", compare("10", "9"), -1);
check("non-ascii", compare("\xc3\xa9", "z"), 1);
check("astral-after-bmp", compare("\xef\xbd\xa1", "\xf0\x9f\x99\x82"), -1);
check("astral", compare("\xf0\x9f\x99\x82", "\xf0\x9f\x99\x83"), -1);
check("combining", compare("cafe\xcc\x81", "caf\xc3\xa9"), -1);
check("eq-same", equals("abc", "abc"), true);
check("eq-case", equals("abc", "ABC"), false);
check("eq-empty", equals("", ""), true);
check("eq-combining", equals("cafe\xcc\x81", "caf\xc3\xa9"), false);
check("eq-astral", equals("\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82"), true);
check("eq-trailing-space", equals("abc", "abc "), false);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
/** Compares strings in the order of their code points. */
public final class Compare {
private Compare() {}
/**
* Returns -1, 0 or 1 for the code point order of a and b. compareTo compares
* UTF-16 code units, so the loop compares code points.
*/
public static int compare(String a, String b) {
int i = 0;
while (i < a.length() && i < b.length()) {
int x = a.codePointAt(i);
int y = b.codePointAt(i);
if (x != y) {
return x < y ? -1 : 1;
}
i += Character.charCount(x);
}
return Integer.signum(a.length() - b.length());
}
/** Returns true if a and b have the same code points. */
public static boolean equals(String a, String b) {
return a.equals(b);
}
}
CompareTest.java 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
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 CompareTest {
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
static Stream<Arguments> order() {
return Stream.of(
Arguments.of("less", "apple", "banana", -1),
Arguments.of("equal", "apple", "apple", 0),
Arguments.of("greater", "pear", "apple", 1),
Arguments.of("both-empty", "", "", 0),
Arguments.of("empty-first", "", "a", -1),
Arguments.of("prefix", "app", "apple", -1),
Arguments.of("prefix-longer", "apple", "app", 1),
Arguments.of("upper-before-lower", "Zebra", "apple", -1),
Arguments.of("lower-after-upper", "a", "A", 1),
Arguments.of("digits", "10", "9", -1),
Arguments.of("non-ascii", "\u00e9", "z", 1),
Arguments.of("astral-after-bmp", "\uff61", "\ud83d\ude42", -1),
Arguments.of("astral", "\ud83d\ude42", "\ud83d\ude43", -1),
Arguments.of("combining", "cafe\u0301", "caf\u00e9", -1));
}
static Stream<Arguments> equal() {
return Stream.of(
Arguments.of("eq-same", "abc", "abc", true),
Arguments.of("eq-case", "abc", "ABC", false),
Arguments.of("eq-empty", "", "", true),
Arguments.of("eq-combining", "cafe\u0301", "caf\u00e9", false),
Arguments.of("eq-astral", "\ud83d\ude42", "\ud83d\ude42", true),
Arguments.of("eq-trailing-space", "abc", "abc ", false));
}
@ParameterizedTest(name = "{0}")
@MethodSource("order")
void compare(String name, String a, String b, int want) {
assertEquals(want, Compare.compare(a, b));
}
@ParameterizedTest(name = "{0}")
@MethodSource("equal")
void equals(String name, String a, String b, boolean want) {
assertEquals(want, Compare.equals(a, b));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
#include "compare.h"
#include <string.h>
int compare(const char *a, const char *b) {
// strcmp compares the bytes as unsigned char, and the order of UTF-8 bytes
// is the order of the code points. The sign is all that strcmp promises.
int r = strcmp(a, b);
return (r > 0) - (r < 0);
}
bool equals(const char *a, const char *b) {
return strcmp(a, b) == 0;
}
compare.h 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
#ifndef COMPARE_H
#define COMPARE_H
#include <stdbool.h>
// compare returns -1, 0 or 1 for the code point order of the UTF-8 strings a
// and b.
int compare(const char *a, const char *b);
// equals reports whether a and b have the same bytes.
bool equals(const char *a, const char *b);
#endif
test_compare.c 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
#include "compare.h"
#include <stdbool.h>
#include <stdio.h>
static int failures = 0;
static void check(const char *name, int got, int want) {
if (got != want) {
fprintf(stderr, "case %s: got %d, want %d\n", name, got, want);
failures++;
}
}
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
int main(void) {
check("less", compare("apple", "banana"), -1);
check("equal", compare("apple", "apple"), 0);
check("greater", compare("pear", "apple"), 1);
check("both-empty", compare("", ""), 0);
check("empty-first", compare("", "a"), -1);
check("prefix", compare("app", "apple"), -1);
check("prefix-longer", compare("apple", "app"), 1);
check("upper-before-lower", compare("Zebra", "apple"), -1);
check("lower-after-upper", compare("a", "A"), 1);
check("digits", compare("10", "9"), -1);
check("non-ascii", compare("\xc3\xa9", "z"), 1);
check("astral-after-bmp", compare("\xef\xbd\xa1", "\xf0\x9f\x99\x82"), -1);
check("astral", compare("\xf0\x9f\x99\x82", "\xf0\x9f\x99\x83"), -1);
check("combining", compare("cafe\xcc\x81", "caf\xc3\xa9"), -1);
check("eq-same", equals("abc", "abc"), true);
check("eq-case", equals("abc", "ABC"), false);
check("eq-empty", equals("", ""), true);
check("eq-combining", equals("cafe\xcc\x81", "caf\xc3\xa9"), false);
check("eq-astral", equals("\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82"), true);
check("eq-trailing-space", equals("abc", "abc "), false);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
using System;
/// <summary>Compares strings in the order of their code points.</summary>
public static class StringOrder
{
// string.CompareOrdinal compares UTF-16 code units, so the loop compares
// code points.
public static int Compare(string a, string b)
{
int i = 0;
while (i < a.Length && i < b.Length)
{
int x = char.ConvertToUtf32(a, i);
int y = char.ConvertToUtf32(b, i);
if (x != y)
{
return x < y ? -1 : 1;
}
i += x > 0xFFFF ? 2 : 1;
}
return Math.Sign(a.Length - b.Length);
}
public static bool AreEqual(string a, string b) => string.Equals(a, b, StringComparison.Ordinal);
}
CompareTests.cs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
using Xunit;
public sealed class CompareTests
{
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
public static TheoryData<string, string, string, int> Order => new()
{
{ "less", "apple", "banana", -1 },
{ "equal", "apple", "apple", 0 },
{ "greater", "pear", "apple", 1 },
{ "both-empty", "", "", 0 },
{ "empty-first", "", "a", -1 },
{ "prefix", "app", "apple", -1 },
{ "prefix-longer", "apple", "app", 1 },
{ "upper-before-lower", "Zebra", "apple", -1 },
{ "lower-after-upper", "a", "A", 1 },
{ "digits", "10", "9", -1 },
{ "non-ascii", "\u00e9", "z", 1 },
{ "astral-after-bmp", "\uff61", "\U0001f642", -1 },
{ "astral", "\U0001f642", "\U0001f643", -1 },
{ "combining", "cafe\u0301", "caf\u00e9", -1 },
};
public static TheoryData<string, string, string, bool> Equal => new()
{
{ "eq-same", "abc", "abc", true },
{ "eq-case", "abc", "ABC", false },
{ "eq-empty", "", "", true },
{ "eq-combining", "cafe\u0301", "caf\u00e9", false },
{ "eq-astral", "\U0001f642", "\U0001f642", true },
{ "eq-trailing-space", "abc", "abc ", false },
};
[Theory]
[MemberData(nameof(Order))]
public void Compares(string name, string a, string b, int want)
{
Assert.NotNull(name);
Assert.Equal(want, StringOrder.Compare(a, b));
}
[Theory]
[MemberData(nameof(Equal))]
public void EqualsTest(string name, string a, string b, bool want)
{
Assert.NotNull(name);
Assert.Equal(want, StringOrder.AreEqual(a, b));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
// compare returns -1, 0 or 1 for the code point order of a and b. The < operator
// compares UTF-16 code units, which puts a code point above U+FFFF before
// U+E000 to U+FFFF, so the loop compares code points.
export function compare(a, b) {
let i = 0;
while (i < a.length && i < b.length) {
const x = a.codePointAt(i);
const y = b.codePointAt(i);
if (x !== y) {
return x < y ? -1 : 1;
}
// The two strings are the same up to here, so one index fits both.
i += x > 0xffff ? 2 : 1;
}
return Math.sign(a.length - b.length);
}
// equals reports whether a and b have the same code points.
export function equals(a, b) {
return a === b;
}
compare.test.js 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { compare, equals } from "./compare.js";
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
const order = [
["less", "apple", "banana", -1],
["equal", "apple", "apple", 0],
["greater", "pear", "apple", 1],
["both-empty", "", "", 0],
["empty-first", "", "a", -1],
["prefix", "app", "apple", -1],
["prefix-longer", "apple", "app", 1],
["upper-before-lower", "Zebra", "apple", -1],
["lower-after-upper", "a", "A", 1],
["digits", "10", "9", -1],
["non-ascii", "\u00e9", "z", 1],
["astral-after-bmp", "\uff61", "\u{1f642}", -1],
["astral", "\u{1f642}", "\u{1f643}", -1],
["combining", "cafe\u0301", "caf\u00e9", -1],
];
const equal = [
["eq-same", "abc", "abc", true],
["eq-case", "abc", "ABC", false],
["eq-empty", "", "", true],
["eq-combining", "cafe\u0301", "caf\u00e9", false],
["eq-astral", "\u{1f642}", "\u{1f642}", true],
["eq-trailing-space", "abc", "abc ", false],
];
for (const [name, a, b, want] of order) {
test(name, () => {
assert.equal(compare(a, b), want);
});
}
for (const [name, a, b, want] of equal) {
test(name, () => {
assert.equal(equals(a, b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
// compare returns -1, 0 or 1 for the code point order of a and b. The < operator
// compares UTF-16 code units, which puts a code point above U+FFFF before
// U+E000 to U+FFFF, so the loop compares code points.
export function compare(a: string, b: string): number {
let i = 0;
while (i < a.length && i < b.length) {
const x = a.codePointAt(i) as number;
const y = b.codePointAt(i) as number;
if (x !== y) {
return x < y ? -1 : 1;
}
// The two strings are the same up to here, so one index fits both.
i += x > 0xffff ? 2 : 1;
}
return Math.sign(a.length - b.length);
}
// equals reports whether a and b have the same code points.
export function equals(a: string, b: string): boolean {
return a === b;
}
compare.test.ts 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { compare, equals } from "./compare.ts";
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
const order = [
["less", "apple", "banana", -1],
["equal", "apple", "apple", 0],
["greater", "pear", "apple", 1],
["both-empty", "", "", 0],
["empty-first", "", "a", -1],
["prefix", "app", "apple", -1],
["prefix-longer", "apple", "app", 1],
["upper-before-lower", "Zebra", "apple", -1],
["lower-after-upper", "a", "A", 1],
["digits", "10", "9", -1],
["non-ascii", "\u00e9", "z", 1],
["astral-after-bmp", "\uff61", "\u{1f642}", -1],
["astral", "\u{1f642}", "\u{1f643}", -1],
["combining", "cafe\u0301", "caf\u00e9", -1],
];
const equal = [
["eq-same", "abc", "abc", true],
["eq-case", "abc", "ABC", false],
["eq-empty", "", "", true],
["eq-combining", "cafe\u0301", "caf\u00e9", false],
["eq-astral", "\u{1f642}", "\u{1f642}", true],
["eq-trailing-space", "abc", "abc ", false],
];
for (const [name, a, b, want] of order) {
test(name, () => {
assert.equal(compare(a, b), want);
});
}
for (const [name, a, b, want] of equal) {
test(name, () => {
assert.equal(equals(a, b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
// Package compare compares strings in the order of their code points.
package compare
import "strings"
// Compare returns -1, 0 or 1. The order of UTF-8 bytes is the order of the
// code points, so the byte compare of strings.Compare is correct.
func Compare(a, b string) int {
return strings.Compare(a, b)
}
// Equals reports whether a and b have the same bytes.
func Equals(a, b string) bool {
return a == b
}
compare_test.go 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
package compare
import "testing"
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
var order = []struct {
name, a, b string
want int
}{
{"less", "apple", "banana", -1},
{"equal", "apple", "apple", 0},
{"greater", "pear", "apple", 1},
{"both-empty", "", "", 0},
{"empty-first", "", "a", -1},
{"prefix", "app", "apple", -1},
{"prefix-longer", "apple", "app", 1},
{"upper-before-lower", "Zebra", "apple", -1},
{"lower-after-upper", "a", "A", 1},
{"digits", "10", "9", -1},
{"non-ascii", "\u00e9", "z", 1},
{"astral-after-bmp", "\uff61", "\U0001f642", -1},
{"astral", "\U0001f642", "\U0001f643", -1},
{"combining", "cafe\u0301", "caf\u00e9", -1},
}
var equal = []struct {
name, a, b string
want bool
}{
{"eq-same", "abc", "abc", true},
{"eq-case", "abc", "ABC", false},
{"eq-empty", "", "", true},
{"eq-combining", "cafe\u0301", "caf\u00e9", false},
{"eq-astral", "\U0001f642", "\U0001f642", true},
{"eq-trailing-space", "abc", "abc ", false},
}
func TestCompare(t *testing.T) {
for _, c := range order {
if got := Compare(c.a, c.b); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
func TestEquals(t *testing.T) {
for _, c := range equal {
if got := Equals(c.a, c.b); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
use std::cmp::Ordering;
/// Returns -1, 0 or 1. The order of str compares the UTF-8 bytes, which is the
/// order of the code points.
pub fn compare(a: &str, b: &str) -> i32 {
match a.cmp(b) {
Ordering::Less => -1,
Ordering::Equal => 0,
Ordering::Greater => 1,
}
}
/// Returns true if a and b have the same code points.
pub fn equals(a: &str, b: &str) -> bool {
a == b
}
tests/compare_test.rs 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-strings/.
use algo_compare_strings::{compare, equals};
// U+FF61 is HALFWIDTH IDEOGRAPHIC FULL STOP. It is before U+1F642 in code point order, but its UTF-16 code unit is after the high surrogate of U+1F642.
#[test]
fn order() {
let cases = [
("less", "apple", "banana", -1),
("equal", "apple", "apple", 0),
("greater", "pear", "apple", 1),
("both-empty", "", "", 0),
("empty-first", "", "a", -1),
("prefix", "app", "apple", -1),
("prefix-longer", "apple", "app", 1),
("upper-before-lower", "Zebra", "apple", -1),
("lower-after-upper", "a", "A", 1),
("digits", "10", "9", -1),
("non-ascii", "\u{e9}", "z", 1),
("astral-after-bmp", "\u{ff61}", "\u{1f642}", -1),
("astral", "\u{1f642}", "\u{1f643}", -1),
("combining", "cafe\u{301}", "caf\u{e9}", -1),
];
for (name, a, b, want) in cases {
assert_eq!(compare(a, b), want, "{name}");
}
}
#[test]
fn equal() {
let cases = [
("eq-same", "abc", "abc", true),
("eq-case", "abc", "ABC", false),
("eq-empty", "", "", true),
("eq-combining", "cafe\u{301}", "caf\u{e9}", false),
("eq-astral", "\u{1f642}", "\u{1f642}", true),
("eq-trailing-space", "abc", "abc ", false),
];
for (name, a, b, want) in cases {
assert_eq!(equals(a, b), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-strings/.
# compare A B: prints -1, 0 or 1. The < operator of [[ uses the order of the
# current locale, so the function sets LC_ALL=C in a subshell, which gives the
# order of the bytes.
compare() {
(
LC_ALL=C
if [[ $1 < $2 ]]; then
printf '%s' -1
elif [[ $1 == "$2" ]]; then
printf '%s' 0
else
printf '%s' 1
fi
)
}
# equals A B: exits with status 0 if A and B are the same string. The quotes
# make B a literal string, not a pattern.
equals() {
[[ $1 == "$2" ]]
}
test_compare.bats 42 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-strings/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/compare.sh"
}
order() { # order WANT A B
run compare "$2" "$3"
[ "$status" -eq 0 ]
[ "$output" = "$1" ]
}
equal() { # equal STATUS A B
run equals "$2" "$3"
[ "$status" -eq "$1" ]
[ "$output" = "" ]
}
# EF BD A1 is U+FF61, and F0 9F 99 82 is U+1F642. The UTF-8 bytes have the order of the code points.
@test "less" { order -1 'apple' 'banana'; }
@test "equal" { order 0 'apple' 'apple'; }
@test "greater" { order 1 'pear' 'apple'; }
@test "both-empty" { order 0 '' ''; }
@test "empty-first" { order -1 '' 'a'; }
@test "prefix" { order -1 'app' 'apple'; }
@test "prefix-longer" { order 1 'apple' 'app'; }
@test "upper-before-lower" { order -1 'Zebra' 'apple'; }
@test "lower-after-upper" { order 1 'a' 'A'; }
@test "digits" { order -1 '10' '9'; }
@test "non-ascii" { order 1 $'\xc3\xa9' 'z'; }
@test "astral-after-bmp" { order -1 $'\xef\xbd\xa1' $'\xf0\x9f\x99\x82'; }
@test "astral" { order -1 $'\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x83'; }
@test "combining" { order -1 $'cafe\xcc\x81' $'caf\xc3\xa9'; }
@test "eq-same" { equal 0 'abc' 'abc'; }
@test "eq-case" { equal 1 'abc' 'ABC'; }
@test "eq-empty" { equal 0 '' ''; }
@test "eq-combining" { equal 1 $'cafe\xcc\x81' $'caf\xc3\xa9'; }
@test "eq-astral" { equal 0 $'\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x82'; }
@test "eq-trailing-space" { equal 1 'abc' 'abc '; }
References
- The Python Language Reference, Expressions, Value comparisons
- MDN Web Docs, Less than (<), Description
- .NET API reference, String.Compare method, Remarks
- Go standard library, package strings, Compare, EqualFold
- The Rust Standard Library, primitive type str, impl Ord for str; eq_ignore_ascii_case
- cppreference.com, strcmp
- Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Bash Conditional Expressions
- The Python Standard Library, Built-in Types, str.casefold
- MDN Web Docs, String.prototype.localeCompare()
- Java SE 25 API, java.lang.String, compareTo(String); equals(Object)
- .NET documentation, Best practices for comparing strings, Recommendations for string usage
- cppreference.com, std::basic_string comparison operators
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 51ENB7 Edit this page History Report an error Markdown