Taskintro
Search for a substring
Also called find a substring, indexOf, contains, string search, strstr, find the position of a substring, rfind, lastIndexOf.
Find the index of the first and the last match of a substring in a string, test whether a string contains a substring, and know the value that each language gives when there is no match.
- Evidence
- Code in 10 languages
Task
Find where a substring occurs in a string. The function find(s, sub) returns the index of the first match of sub in s, and -1 if there is no match. The second function, find_last(s, sub), returns the index of the last match. For example, find("abcabc", "bc") is 1 and find_last("abcabc", "bc") is 4. The empty string matches at each position, so find(s, "") is 0 and find_last(s, "") is the length of s.
The indexes count code points, as in Get a substring, so that the result is the same in each language. The search functions of most languages return an index in another unit. 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. So each solution converts the index of the built-in search to code points.
Solutions
| Language | First match | Last match | No match | Test only |
|---|---|---|---|---|
| Python | s.find(sub) |
s.rfind(sub) |
-1 | sub in s |
| JavaScript, TypeScript | s.indexOf(sub) |
s.lastIndexOf(sub) |
-1 | s.includes(sub) |
| Java | s.indexOf(sub) |
s.lastIndexOf(sub) |
-1 | s.contains(sub) |
| C# | s.IndexOf(sub, StringComparison.Ordinal) |
s.LastIndexOf(sub, StringComparison.Ordinal) |
-1 | s.Contains(sub) |
| Go | strings.Index(s, sub) |
strings.LastIndex(s, sub) |
-1 | strings.Contains(s, sub) |
| Rust | s.find(sub) |
s.rfind(sub) |
None |
s.contains(sub) |
| C | strstr(s, sub) |
a loop of strstr |
NULL |
strstr(s, sub) != NULL |
| C++ | s.find(sub) |
s.rfind(sub) |
npos |
s.contains(sub) |
| Bash | ${s%%"$sub"*} |
${s%"$sub"*} |
no built-in value | [[ $s == *"$sub"* ]] |
- Python.
findreturns "the lowest index in the string where substring sub is found within the slice s[start:end]"1, and it returns -1 if sub is not found1. Astrcounts code points, so the result needs no conversion.rfindgives the last match. - JavaScript and TypeScript.
indexOfreturns "The index of the first occurrence of searchString found, or -1 if not found"5. The index counts code units, so the code counts the code points ins.slice(0, i)withArray.from. A match of a well-formed string starts at a code point, so the slice does not cut a surrogate pair. - Java.
indexOf"Returns the index within this string of the first occurrence of the specified substring"3, incharvalues.codePointCount(0, i)converts the index to code points. - C#. The overloads of
IndexOfwith noStringComparisonargument do a culture-sensitive search: "This method performs a word (case-sensitive and culture-sensitive) search using the current culture"6. The .NET guide says "Use overloads that explicitly specify the string comparison rules for string operations"7, so the code passesStringComparison.Ordinal. Then it counts the UTF-16 code units of the prefix that are not low surrogates. For an emptysub,FindLastreturns the length in code points without a call. - Go. "Index returns the index of the first instance of substr in s, or -1 if substr is not present in s"8. The index counts bytes, so the code counts the code points of
s[:i]withutf8.RuneCountInString. - Rust.
find"Returns the byte index of the first character of this string slice that matches the pattern. Returns None if the pattern doesn’t match"9. The code counts the chars ofs[..i]and mapsNoneto -1. - C.
strstrreturns a "Pointer to the first character of the found substring in str, or a null pointer if such substring is not found"10. The code counts the code points in the bytes before the match. Each byte that does not have the form10xxxxxxstarts a code point11. C has no reversestrstr, sofind_lastsearches again from the byte after each match. - C++.
findreturns the "Position of the first character of the found substring or npos if no such substring is found"12.rfindgives the last match. The code counts the code points before the position in the same way as the C code. - Bash. The
%%expansion deletes "the longest matching pattern"13 at the end of the value, and the%expansion deletes the shortest one. The pattern is the quotedsuband a*after it, so the rest is the text before the first or the last match, and its length is the index. The function tests for a match first with[[ ... ]], and it counts the length withLC_ALL=C.UTF-8, where each code point is one character.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of find_last are in cases/last.jsonl.
empty-sub,empty-sandboth-empty: the empty string matches at index 0 of each string, also of the empty string. A search for a non-empty string in the empty string gives -1.longer-sub: a substring that is longer than the string cannot match.overlapandlast-overlap: inaaaa, the matches ofaaoverlap. The first match is at 0, and the last match is at 2, not at 1.case-sensitive: the search compares code points, sohellodoes not matchHello. Convert both strings with Change the case of a string for a search that ignores case.non-asciiandcjk: the index in code points is smaller than the index in bytes after the first character that is not ASCII.astralandastral-sub: an emoji is one code point and two UTF-16 code units, so a solution that returns the index ofindexOfgives 3, not 2.combiningandprecomposed:cafe\u0301ends witheand a combining accent. A search forefinds the base letter, and a search for the precomposed\u00e9finds nothing, although a reader sees the same text. Use Normalize Unicode text before a search if the text can have both forms.
Pitfalls
- Python find returns -1, and -1 is a valid index.
s[s.find(x)]gives the last character when there is no match. Useindex, which is "Like find(), but raise ValueError when the substring is not found"1. To test only, "use the in operator"1:
s = "Hello"
print("ell" in s, "" in s, s.find("x"), s.rfind("l"))
i = s.find("x")
print(repr(s[i]))
try:
s.index("x")
except ValueError as e:
print("ValueError:", e)
True True -1 3
'o'
ValueError: substring not found
- JavaScript indexOf returns 0 for a match at the start. 0 is false in a condition, and -1 is true, so
if (t.indexOf(x))is wrong in both directions. MDN says that "the correct way to check is test whether the return value is -1"5.includesreturns a boolean, and it "performs a case-sensitive search"14:
const s = "\u{1F642}b";
console.log(s.indexOf("b"), Array.from(s).indexOf("b"));
const t = "apple";
if (t.indexOf("a")) {
console.log("found a");
} else {
console.log("no a? indexOf gave", t.indexOf("a"));
}
console.log(t.includes("a"), t.indexOf("x"));
2 1
no a? indexOf gave 0
true -1
- Java indexOf counts char values, not code points. After an emoji, the index is one larger than the number of code points.
contains"Returns true if and only if this string contains the specified sequence of char values"3:
public class Main {
public static void main(String[] args) {
String s = "🙂b";
int i = s.indexOf("b");
System.out.println(i + " " + s.codePointCount(0, i));
System.out.println("Hello".indexOf("L") + " " + "Hello".toLowerCase().indexOf("l"));
System.out.println("Hello".contains("ell"));
}
}
2 1
-1 2
true
- C# IndexOf of a string uses the current culture. A culture-sensitive search ignores some characters, such as the soft hyphen U+00AD, so it finds a match that an ordinal search does not find.
Containsdoes an ordinal search. PassStringComparison.OrdinaltoIndexOf:
// U+00AD is SOFT HYPHEN, an ignorable character in a culture-sensitive search.
string s = "animal";
Console.WriteLine(s.IndexOf("\u00ADn"));
Console.WriteLine(s.IndexOf("\u00ADn", StringComparison.Ordinal));
Console.WriteLine(s.IndexOf("\u00AD"));
Console.WriteLine(s.Contains("\u00ADn"));
1
-1
0
False
- Go strings.Index returns a byte index. For
naïve café, the match ofcaféis at byte 7 and at code point 6. Use the byte index to slice the string, and count the runes only to show a position to a reader:
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
s := "naïve café"
i := strings.Index(s, "café")
fmt.Println(i, utf8.RuneCountInString(s[:i]))
fmt.Println(strings.Contains(s, "ïv"), strings.Index(s, "x"))
fmt.Println(strings.Index(strings.ToLower("Café"), "café"))
}
7 6
true -1
0
- Rust find returns an Option of a byte index. "The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches"9, so
find(char::is_whitespace)works:
fn main() {
let s = "naïve café";
println!("{:?} {:?}", s.find("café"), s.find("x"));
println!("{:?} {:?}", s.find('é'), s.find(char::is_whitespace));
let i = s.find("café").unwrap();
println!("{}", s[..i].chars().count());
}
Some(7) None
Some(10) Some(6)
6
- C strstr returns a pointer. Check it for a null pointer before you use it, and subtract the start of the string to get the byte index. "If substr points to an empty string, str is returned"10:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s = "Hello, world";
const char *p = strstr(s, "world");
if (p != NULL) {
printf("found at byte %td: %s\n", p - s, p);
}
printf("%s\n", strstr(s, "x") == NULL ? "NULL" : "found");
printf("%td\n", strstr(s, "") - s);
}
found at byte 7: world
NULL
0
- C++ find returns npos, not -1.
nposis the largest value ofstd::size_t, and a match at the start is 0, soif (s.find(x))is wrong in both directions. Compare withnpos, or usecontains, which "Checks if the string contains the given substring"15 (C++23):
#include <print>
#include <string>
int main() {
std::string s = "Hello";
std::size_t i = s.find("x");
std::println("{} {}", i == std::string::npos, i);
if (s.find("H")) {
std::println("H found");
} else {
std::println("no H? find gave {}", s.find("H"));
}
std::println("{} {}", s.contains("ell"), s.rfind('l'));
}
true 18446744073709551615
no H? find gave 0
true 3
- Bash treats an unquoted variable as a pattern. In
[[ $s == *$sub* ]], a*insubmatches any text. "If you quote any part of the pattern, using any of the shell’s quoting mechanisms, the quoted portion is matched literally"13:
s=abc
sub='a*'
[[ $s == *$sub* ]] && echo "unquoted: match"
[[ $s == *"$sub"* ]] || echo "quoted: no match"
s='a*c'
[[ $s == *"$sub"* ]] && echo "quoted: match in a*c"
unquoted: match
quoted: no match
quoted: match in a*c
Related tasks
- Get a substring: cut the text at the index that a search returns.
- Split a string: cut a string at each match of a separator.
- Replace a substring: change each match of a substring.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-for-a-substring/.
def find(s: str, sub: str) -> int:
"""Return the code point index of the first match of sub in s, or -1."""
# A str is a sequence of code points, so str.find counts code points.
return s.find(sub)
def find_last(s: str, sub: str) -> int:
"""Return the code point index of the last match of sub in s, or -1."""
return s.rfind(sub)
test_search.py 46 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-for-a-substring/.
import pytest
from search import find, find_last
# U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
FIRST = {
"found": ("Hello, world", "world", 7),
"first-of-two": ("abcabc", "bc", 1),
"not-found": ("abc", "d", -1),
"empty-sub": ("abc", "", 0),
"empty-s": ("", "a", -1),
"both-empty": ("", "", 0),
"longer-sub": ("ab", "abc", -1),
"overlap": ("aaaa", "aa", 0),
"case-sensitive": ("Hello", "hello", -1),
"non-ascii": ("naïve caf\u00e9", "caf\u00e9", 6),
"cjk": ("日本語テキスト", "テキ", 3),
"astral": ("a\U0001f642b\U0001f642c", "b", 2),
"astral-sub": ("x\U0001f642y", "\U0001f642y", 1),
"combining": ("cafe\u0301", "e", 3),
"precomposed": ("cafe\u0301", "\u00e9", -1),
}
LAST = {
"last-of-two": ("abcabc", "bc", 4),
"last-not-found": ("abc", "d", -1),
"last-empty-sub": ("abc", "", 3),
"last-empty-s": ("", "", 0),
"last-overlap": ("aaaa", "aa", 2),
"last-astral": ("\U0001f642a\U0001f642a", "a", 3),
"last-non-ascii": ("caf\u00e9 caf\u00e9", "\u00e9", 8),
}
@pytest.mark.parametrize("name", FIRST)
def test_find(name):
s, sub, want = FIRST[name]
assert find(s, sub) == want
@pytest.mark.parametrize("name", LAST)
def test_find_last(name):
s, sub, want = LAST[name]
assert find_last(s, sub) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
#include "search.hpp"
#include <algorithm>
namespace {
// code_points counts the code points in the first n bytes of s. Each byte that
// does not have the form 10xxxxxx starts a code point.
long code_points(std::string_view s, std::size_t n) {
return static_cast<long>(std::count_if(s.begin(), s.begin() + static_cast<std::ptrdiff_t>(n),
[](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; }));
}
} // namespace
long find(std::string_view s, std::string_view sub) {
// find returns a byte index, so count the code points before it.
std::size_t i = s.find(sub);
return i == std::string_view::npos ? -1 : code_points(s, i);
}
long find_last(std::string_view s, std::string_view sub) {
std::size_t i = s.rfind(sub);
return i == std::string_view::npos ? -1 : code_points(s, i);
}
search.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
#ifndef SEARCH_HPP
#define SEARCH_HPP
#include <string_view>
// find returns the code point index of the first match of the UTF-8 string sub
// in the UTF-8 string s, or -1 if there is no match.
long find(std::string_view s, std::string_view sub);
// find_last returns the code point index of the last match of sub in s, or -1.
long find_last(std::string_view s, std::string_view sub);
#endif
test_search.cpp 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
#include "search.hpp"
#include <iostream>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, long got, long 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("found", find("Hello, world", "world"), 7);
check("first-of-two", find("abcabc", "bc"), 1);
check("not-found", find("abc", "d"), -1);
check("empty-sub", find("abc", ""), 0);
check("empty-s", find("", "a"), -1);
check("both-empty", find("", ""), 0);
check("longer-sub", find("ab", "abc"), -1);
check("overlap", find("aaaa", "aa"), 0);
check("case-sensitive", find("Hello", "hello"), -1);
check("non-ascii", find("naïve caf\xc3\xa9", "caf\xc3\xa9"), 6);
check("cjk", find("日本語テキスト", "テキ"), 3);
check("astral", find("a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x82" "c", "b"), 2);
check("astral-sub", find("x\xf0\x9f\x99\x82y", "\xf0\x9f\x99\x82y"), 1);
check("combining", find("cafe\xcc\x81", "e"), 3);
check("precomposed", find("cafe\xcc\x81", "\xc3\xa9"), -1);
check("last-of-two", find_last("abcabc", "bc"), 4);
check("last-not-found", find_last("abc", "d"), -1);
check("last-empty-sub", find_last("abc", ""), 3);
check("last-empty-s", find_last("", ""), 0);
check("last-overlap", find_last("aaaa", "aa"), 2);
check("last-astral", find_last("\xf0\x9f\x99\x82" "a\xf0\x9f\x99\x82" "a", "a"), 3);
check("last-non-ascii", find_last("caf\xc3\xa9 caf\xc3\xa9", "\xc3\xa9"), 8);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
/** Searches a string for a substring, with indexes in code points. */
public final class Search {
private Search() {}
/** Returns the code point index of the first match of sub in s, or -1. */
public static int find(String s, String sub) {
// indexOf counts UTF-16 code units, so convert the index to code points.
int i = s.indexOf(sub);
return i < 0 ? -1 : s.codePointCount(0, i);
}
/** Returns the code point index of the last match of sub in s, or -1. */
public static int findLast(String s, String sub) {
int i = s.lastIndexOf(sub);
return i < 0 ? -1 : s.codePointCount(0, i);
}
}
SearchTest.java 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-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 SearchTest {
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
static Stream<Arguments> first() {
return Stream.of(
Arguments.of("found", "Hello, world", "world", 7),
Arguments.of("first-of-two", "abcabc", "bc", 1),
Arguments.of("not-found", "abc", "d", -1),
Arguments.of("empty-sub", "abc", "", 0),
Arguments.of("empty-s", "", "a", -1),
Arguments.of("both-empty", "", "", 0),
Arguments.of("longer-sub", "ab", "abc", -1),
Arguments.of("overlap", "aaaa", "aa", 0),
Arguments.of("case-sensitive", "Hello", "hello", -1),
Arguments.of("non-ascii", "naïve caf\u00e9", "caf\u00e9", 6),
Arguments.of("cjk", "日本語テキスト", "テキ", 3),
Arguments.of("astral", "a\ud83d\ude42b\ud83d\ude42c", "b", 2),
Arguments.of("astral-sub", "x\ud83d\ude42y", "\ud83d\ude42y", 1),
Arguments.of("combining", "cafe\u0301", "e", 3),
Arguments.of("precomposed", "cafe\u0301", "\u00e9", -1));
}
static Stream<Arguments> last() {
return Stream.of(
Arguments.of("last-of-two", "abcabc", "bc", 4),
Arguments.of("last-not-found", "abc", "d", -1),
Arguments.of("last-empty-sub", "abc", "", 3),
Arguments.of("last-empty-s", "", "", 0),
Arguments.of("last-overlap", "aaaa", "aa", 2),
Arguments.of("last-astral", "\ud83d\ude42a\ud83d\ude42a", "a", 3),
Arguments.of("last-non-ascii", "caf\u00e9 caf\u00e9", "\u00e9", 8));
}
@ParameterizedTest(name = "{0}")
@MethodSource("first")
void find(String name, String s, String sub, int want) {
assertEquals(want, Search.find(s, sub));
}
@ParameterizedTest(name = "{0}")
@MethodSource("last")
void findLast(String name, String s, String sub, int want) {
assertEquals(want, Search.findLast(s, sub));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
#include "search.h"
#include <string.h>
// code_points counts the code points in the n bytes at s. Each byte that does
// not have the form 10xxxxxx starts a code point.
static long code_points(const char *s, size_t n) {
long count = 0;
for (size_t i = 0; i < n; i++) {
if (((unsigned char)s[i] & 0xC0) != 0x80) {
count++;
}
}
return count;
}
long find(const char *s, const char *sub) {
const char *p = strstr(s, sub);
return p == NULL ? -1 : code_points(s, (size_t)(p - s));
}
long find_last(const char *s, const char *sub) {
// C has no reverse strstr, so search again after each match.
const char *last = NULL;
for (const char *p = strstr(s, sub); p != NULL; p = strstr(p + 1, sub)) {
last = p;
if (*p == '\0') {
break;
}
}
return last == NULL ? -1 : code_points(s, (size_t)(last - s));
}
search.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
#ifndef SEARCH_H
#define SEARCH_H
// find returns the code point index of the first match of the UTF-8 string sub
// in the UTF-8 string s, or -1 if there is no match.
long find(const char *s, const char *sub);
// find_last returns the code point index of the last match of sub in s, or -1.
long find_last(const char *s, const char *sub);
#endif
test_search.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
#include "search.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, long got, long want) {
if (got != want) {
fprintf(stderr, "case %s: got %ld, want %ld\n", name, got, want);
failures++;
}
}
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
int main(void) {
check("found", find("Hello, world", "world"), 7);
check("first-of-two", find("abcabc", "bc"), 1);
check("not-found", find("abc", "d"), -1);
check("empty-sub", find("abc", ""), 0);
check("empty-s", find("", "a"), -1);
check("both-empty", find("", ""), 0);
check("longer-sub", find("ab", "abc"), -1);
check("overlap", find("aaaa", "aa"), 0);
check("case-sensitive", find("Hello", "hello"), -1);
check("non-ascii", find("naïve caf\xc3\xa9", "caf\xc3\xa9"), 6);
check("cjk", find("日本語テキスト", "テキ"), 3);
check("astral", find("a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x82" "c", "b"), 2);
check("astral-sub", find("x\xf0\x9f\x99\x82y", "\xf0\x9f\x99\x82y"), 1);
check("combining", find("cafe\xcc\x81", "e"), 3);
check("precomposed", find("cafe\xcc\x81", "\xc3\xa9"), -1);
check("last-of-two", find_last("abcabc", "bc"), 4);
check("last-not-found", find_last("abc", "d"), -1);
check("last-empty-sub", find_last("abc", ""), 3);
check("last-empty-s", find_last("", ""), 0);
check("last-overlap", find_last("aaaa", "aa"), 2);
check("last-astral", find_last("\xf0\x9f\x99\x82" "a\xf0\x9f\x99\x82" "a", "a"), 3);
check("last-non-ascii", find_last("caf\xc3\xa9 caf\xc3\xa9", "\xc3\xa9"), 8);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
using System;
/// <summary>Searches a string for a substring, with indexes in code points.</summary>
public static class Search
{
/// <summary>Returns the code point index of the first match of sub in s, or -1.</summary>
public static int Find(string s, string sub)
{
// IndexOf(string) with no StringComparison uses the current culture,
// so the code asks for an ordinal search.
int i = s.IndexOf(sub, StringComparison.Ordinal);
return i < 0 ? -1 : CodePoints(s, i);
}
/// <summary>Returns the code point index of the last match of sub in s, or -1.</summary>
public static int FindLast(string s, string sub)
{
if (sub.Length == 0)
{
return CodePoints(s, s.Length);
}
int i = s.LastIndexOf(sub, StringComparison.Ordinal);
return i < 0 ? -1 : CodePoints(s, i);
}
// CodePoints counts the code points in the first end UTF-16 code units of s.
private static int CodePoints(string s, int end)
{
int n = 0;
for (int i = 0; i < end; i++)
{
if (!char.IsLowSurrogate(s[i]))
{
n++;
}
}
return n;
}
}
SearchTests.cs 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
using Xunit;
public sealed class SearchTests
{
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
public static TheoryData<string, string, string, int> First => new()
{
{ "found", "Hello, world", "world", 7 },
{ "first-of-two", "abcabc", "bc", 1 },
{ "not-found", "abc", "d", -1 },
{ "empty-sub", "abc", "", 0 },
{ "empty-s", "", "a", -1 },
{ "both-empty", "", "", 0 },
{ "longer-sub", "ab", "abc", -1 },
{ "overlap", "aaaa", "aa", 0 },
{ "case-sensitive", "Hello", "hello", -1 },
{ "non-ascii", "naïve caf\u00e9", "caf\u00e9", 6 },
{ "cjk", "日本語テキスト", "テキ", 3 },
{ "astral", "a\U0001f642b\U0001f642c", "b", 2 },
{ "astral-sub", "x\U0001f642y", "\U0001f642y", 1 },
{ "combining", "cafe\u0301", "e", 3 },
{ "precomposed", "cafe\u0301", "\u00e9", -1 },
};
public static TheoryData<string, string, string, int> Last => new()
{
{ "last-of-two", "abcabc", "bc", 4 },
{ "last-not-found", "abc", "d", -1 },
{ "last-empty-sub", "abc", "", 3 },
{ "last-empty-s", "", "", 0 },
{ "last-overlap", "aaaa", "aa", 2 },
{ "last-astral", "\U0001f642a\U0001f642a", "a", 3 },
{ "last-non-ascii", "caf\u00e9 caf\u00e9", "\u00e9", 8 },
};
[Theory]
[MemberData(nameof(First))]
public void Find(string name, string s, string sub, int want)
{
Assert.NotNull(name);
Assert.Equal(want, Search.Find(s, sub));
}
[Theory]
[MemberData(nameof(Last))]
public void FindLast(string name, string s, string sub, int want)
{
Assert.NotNull(name);
Assert.Equal(want, Search.FindLast(s, sub));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
// indexOf and lastIndexOf count UTF-16 code units. A match of a well-formed
// string starts at a code point, so the code counts the code points before it.
const codePoints = (s, end) => Array.from(s.slice(0, end)).length;
/** Returns the code point index of the first match of sub in s, or -1. */
export function find(s, sub) {
const i = s.indexOf(sub);
return i < 0 ? -1 : codePoints(s, i);
}
/** Returns the code point index of the last match of sub in s, or -1. */
export function findLast(s, sub) {
const i = s.lastIndexOf(sub);
return i < 0 ? -1 : codePoints(s, i);
}
search.test.js 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { find, findLast } from "./search.js";
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const first = [
["found", "Hello, world", "world", 7],
["first-of-two", "abcabc", "bc", 1],
["not-found", "abc", "d", -1],
["empty-sub", "abc", "", 0],
["empty-s", "", "a", -1],
["both-empty", "", "", 0],
["longer-sub", "ab", "abc", -1],
["overlap", "aaaa", "aa", 0],
["case-sensitive", "Hello", "hello", -1],
["non-ascii", "naïve caf\u00e9", "caf\u00e9", 6],
["cjk", "日本語テキスト", "テキ", 3],
["astral", "a\u{1f642}b\u{1f642}c", "b", 2],
["astral-sub", "x\u{1f642}y", "\u{1f642}y", 1],
["combining", "cafe\u0301", "e", 3],
["precomposed", "cafe\u0301", "\u00e9", -1],
];
const last = [
["last-of-two", "abcabc", "bc", 4],
["last-not-found", "abc", "d", -1],
["last-empty-sub", "abc", "", 3],
["last-empty-s", "", "", 0],
["last-overlap", "aaaa", "aa", 2],
["last-astral", "\u{1f642}a\u{1f642}a", "a", 3],
["last-non-ascii", "caf\u00e9 caf\u00e9", "\u00e9", 8],
];
for (const [name, s, sub, want] of first) {
test(name, () => {
assert.equal(find(s, sub), want);
});
}
for (const [name, s, sub, want] of last) {
test(name, () => {
assert.equal(findLast(s, sub), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
// indexOf and lastIndexOf count UTF-16 code units. A match of a well-formed
// string starts at a code point, so the code counts the code points before it.
const codePoints = (s: string, end: number): number => Array.from(s.slice(0, end)).length;
/** Returns the code point index of the first match of sub in s, or -1. */
export function find(s: string, sub: string): number {
const i = s.indexOf(sub);
return i < 0 ? -1 : codePoints(s, i);
}
/** Returns the code point index of the last match of sub in s, or -1. */
export function findLast(s: string, sub: string): number {
const i = s.lastIndexOf(sub);
return i < 0 ? -1 : codePoints(s, i);
}
search.test.ts 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { find, findLast } from "./search.ts";
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const first = [
["found", "Hello, world", "world", 7],
["first-of-two", "abcabc", "bc", 1],
["not-found", "abc", "d", -1],
["empty-sub", "abc", "", 0],
["empty-s", "", "a", -1],
["both-empty", "", "", 0],
["longer-sub", "ab", "abc", -1],
["overlap", "aaaa", "aa", 0],
["case-sensitive", "Hello", "hello", -1],
["non-ascii", "naïve caf\u00e9", "caf\u00e9", 6],
["cjk", "日本語テキスト", "テキ", 3],
["astral", "a\u{1f642}b\u{1f642}c", "b", 2],
["astral-sub", "x\u{1f642}y", "\u{1f642}y", 1],
["combining", "cafe\u0301", "e", 3],
["precomposed", "cafe\u0301", "\u00e9", -1],
];
const last = [
["last-of-two", "abcabc", "bc", 4],
["last-not-found", "abc", "d", -1],
["last-empty-sub", "abc", "", 3],
["last-empty-s", "", "", 0],
["last-overlap", "aaaa", "aa", 2],
["last-astral", "\u{1f642}a\u{1f642}a", "a", 3],
["last-non-ascii", "caf\u00e9 caf\u00e9", "\u00e9", 8],
];
for (const [name, s, sub, want] of first) {
test(name, () => {
assert.equal(find(s, sub), want);
});
}
for (const [name, s, sub, want] of last) {
test(name, () => {
assert.equal(findLast(s, sub), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
// Package search finds a substring in a string, with indexes in code points.
package search
import (
"strings"
"unicode/utf8"
)
// Find returns the code point index of the first match of sub in s, or -1.
func Find(s, sub string) int {
// strings.Index returns a byte index, so count the code points before it.
i := strings.Index(s, sub)
if i < 0 {
return -1
}
return utf8.RuneCountInString(s[:i])
}
// FindLast returns the code point index of the last match of sub in s, or -1.
func FindLast(s, sub string) int {
i := strings.LastIndex(s, sub)
if i < 0 {
return -1
}
return utf8.RuneCountInString(s[:i])
}
search_test.go 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
package search
import "testing"
type searchCase struct {
name, s, sub string
want int
}
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
var first = []searchCase{
{"found", "Hello, world", "world", 7},
{"first-of-two", "abcabc", "bc", 1},
{"not-found", "abc", "d", -1},
{"empty-sub", "abc", "", 0},
{"empty-s", "", "a", -1},
{"both-empty", "", "", 0},
{"longer-sub", "ab", "abc", -1},
{"overlap", "aaaa", "aa", 0},
{"case-sensitive", "Hello", "hello", -1},
{"non-ascii", "naïve caf\u00e9", "caf\u00e9", 6},
{"cjk", "日本語テキスト", "テキ", 3},
{"astral", "a\U0001f642b\U0001f642c", "b", 2},
{"astral-sub", "x\U0001f642y", "\U0001f642y", 1},
{"combining", "cafe\u0301", "e", 3},
{"precomposed", "cafe\u0301", "\u00e9", -1},
}
var last = []searchCase{
{"last-of-two", "abcabc", "bc", 4},
{"last-not-found", "abc", "d", -1},
{"last-empty-sub", "abc", "", 3},
{"last-empty-s", "", "", 0},
{"last-overlap", "aaaa", "aa", 2},
{"last-astral", "\U0001f642a\U0001f642a", "a", 3},
{"last-non-ascii", "caf\u00e9 caf\u00e9", "\u00e9", 8},
}
func TestFind(t *testing.T) {
for _, c := range first {
if got := Find(c.s, c.sub); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
func TestFindLast(t *testing.T) {
for _, c := range last {
if got := FindLast(c.s, c.sub); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
/// Returns the code point index of the first match of sub in s, or -1.
pub fn find(s: &str, sub: &str) -> i64 {
// str::find returns a byte index, so count the chars before it.
s.find(sub).map_or(-1, |i| s[..i].chars().count() as i64)
}
/// Returns the code point index of the last match of sub in s, or -1.
pub fn find_last(s: &str, sub: &str) -> i64 {
s.rfind(sub).map_or(-1, |i| s[..i].chars().count() as i64)
}
tests/search_test.rs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-for-a-substring/.
use algo_search_for_a_substring::{find, find_last};
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
#[test]
fn first() {
let cases = [
("found", "Hello, world", "world", 7),
("first-of-two", "abcabc", "bc", 1),
("not-found", "abc", "d", -1),
("empty-sub", "abc", "", 0),
("empty-s", "", "a", -1),
("both-empty", "", "", 0),
("longer-sub", "ab", "abc", -1),
("overlap", "aaaa", "aa", 0),
("case-sensitive", "Hello", "hello", -1),
("non-ascii", "naïve caf\u{e9}", "caf\u{e9}", 6),
("cjk", "日本語テキスト", "テキ", 3),
("astral", "a\u{1f642}b\u{1f642}c", "b", 2),
("astral-sub", "x\u{1f642}y", "\u{1f642}y", 1),
("combining", "cafe\u{301}", "e", 3),
("precomposed", "cafe\u{301}", "\u{e9}", -1),
];
for (name, s, sub, want) in cases {
assert_eq!(find(s, sub), want, "{name}");
}
}
#[test]
fn last() {
let cases = [
("last-of-two", "abcabc", "bc", 4),
("last-not-found", "abc", "d", -1),
("last-empty-sub", "abc", "", 3),
("last-empty-s", "", "", 0),
("last-overlap", "aaaa", "aa", 2),
("last-astral", "\u{1f642}a\u{1f642}a", "a", 3),
("last-non-ascii", "caf\u{e9} caf\u{e9}", "\u{e9}", 8),
];
for (name, s, sub, want) in cases {
assert_eq!(find_last(s, sub), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-for-a-substring/.
# find S SUB: prints the code point index of the first match of SUB in S, or
# -1. ${s%%"$sub"*} removes the longest suffix that starts with SUB, so the rest
# is the text before the first match. The quotes make SUB a literal string,
# not a pattern. The length runs in the locale C.UTF-8, where each code point
# is one character.
find() {
(
LC_ALL=C.UTF-8
if [[ $1 != *"$2"* ]]; then
echo -1
return
fi
local before=${1%%"$2"*}
echo "${#before}"
)
}
# find_last S SUB: prints the code point index of the last match of SUB in S,
# or -1. ${s%"$sub"*} removes the shortest suffix that starts with SUB.
find_last() {
(
LC_ALL=C.UTF-8
if [[ $1 != *"$2"* ]]; then
echo -1
return
fi
local before=${1%"$2"*}
echo "${#before}"
)
}
test_search.bats 38 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-for-a-substring/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/search.sh"
}
check() { # check WANT FUNCTION S SUB
run "$2" "$3" "$4"
[ "$status" -eq 0 ]
[ "$output" = "$1" ]
}
# CC 81 is U+0301 COMBINING ACUTE ACCENT, and C3 A9 is U+00E9.
@test "found" { check 7 find 'Hello, world' 'world'; }
@test "first-of-two" { check 1 find 'abcabc' 'bc'; }
@test "not-found" { check -1 find 'abc' 'd'; }
@test "empty-sub" { check 0 find 'abc' ''; }
@test "empty-s" { check -1 find '' 'a'; }
@test "both-empty" { check 0 find '' ''; }
@test "longer-sub" { check -1 find 'ab' 'abc'; }
@test "overlap" { check 0 find 'aaaa' 'aa'; }
@test "case-sensitive" { check -1 find 'Hello' 'hello'; }
@test "non-ascii" { check 6 find $'naïve caf\xc3\xa9' $'caf\xc3\xa9'; }
@test "cjk" { check 3 find '日本語テキスト' 'テキ'; }
@test "astral" { check 2 find $'a\xf0\x9f\x99\x82b\xf0\x9f\x99\x82c' 'b'; }
@test "astral-sub" { check 1 find $'x\xf0\x9f\x99\x82y' $'\xf0\x9f\x99\x82y'; }
@test "combining" { check 3 find $'cafe\xcc\x81' 'e'; }
@test "precomposed" { check -1 find $'cafe\xcc\x81' $'\xc3\xa9'; }
@test "last-of-two" { check 4 find_last 'abcabc' 'bc'; }
@test "last-not-found" { check -1 find_last 'abc' 'd'; }
@test "last-empty-sub" { check 3 find_last 'abc' ''; }
@test "last-empty-s" { check 0 find_last '' ''; }
@test "last-overlap" { check 2 find_last 'aaaa' 'aa'; }
@test "last-astral" { check 3 find_last $'\xf0\x9f\x99\x82a\xf0\x9f\x99\x82a' 'a'; }
@test "last-non-ascii" { check 8 find_last $'caf\xc3\xa9 caf\xc3\xa9' $'\xc3\xa9'; }
References
- The Python Standard Library, Built-in Types, str.find, str.index, str.rfind
- MDN Web Docs, String, UTF-16 characters, Unicode code points, and grapheme clusters
- Java SE 25 API, java.lang.String, indexOf(String); contains; codePointCount
- .NET API reference, Char struct
- MDN Web Docs, String.prototype.indexOf(), Return value; Checking occurrences
- .NET API reference, String.IndexOf method
- .NET fundamentals, Best practices for comparing strings in .NET
- Go standard library, package strings, Index, LastIndex, Contains
- The Rust Standard Library, primitive type str, find, rfind, contains
- cppreference.com, strstr
- RFC 3629, UTF-8, a transformation format of ISO 10646, Section 3
- cppreference.com, std::basic_string find
- Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Conditional Constructs; Shell Parameter Expansion
- MDN Web Docs, String.prototype.includes()
- cppreference.com, std::basic_string contains
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 APAQPG Edit this page History Report an error Markdown