Taskcore
Split a string
Also called split a string on a delimiter, tokenize a string, split a string into fields, explode a string.
Split a string into fields on a literal separator, keep the empty fields, stop after a limit, and also split on white space and on a regular expression.
- Evidence
- Code in 10 languages
Task
Split a string into fields on a separator. The separator is a literal string of one or more characters. It is not a pattern, so a . or a | in it matches only itself.
Keep every empty field. Two separators side by side give an empty field between them. A separator at the start or at the end gives an empty field there. So a string with k separators gives k + 1 fields, and the empty string gives one empty field. In data such as CSV an empty field is a value, so the split must keep it.
The search for the separator goes from left to right, and two matches do not overlap. So "aaa" split on "aa" gives "" and "a".
A limit n stops the split after n - 1 separators. The last field then holds the rest of the string, with its separators. A limit of 0 means no limit.
Each solution also has two related functions. split_whitespace splits on runs of white space and gives no empty fields, as when you read words. split_regex splits on each match of a regular expression, with the same rules as the main function and no limit.
Solutions
- Python.
s.split(sep, maxsplit)keeps empty fields and puts the rest in the last field. Itsmaxsplitcounts splits, not fields, so the code passeslimit - 1.s.split()with no separator splits on runs of white space.re.splitsplits on a regular expression. - JavaScript and TypeScript.
s.split(sep)keeps empty fields. Itslimitargument drops the rest of the string, so the code splits fully and joins the rest again.s.split(/\s+/)with a filter splits on white space, andsplitwith aRegExpsplits on a pattern. The TypeScript file adds types only. - Java.
String.splittakes a regular expression, so the code quotes the separator withPattern.quote. A limit of 0 removes the trailing empty strings, so the code gives -1 for no limit.Pattern.split(s, -1)splits on a pattern. - C#.
s.Split(sep)ands.Split(sep, count)take a string separator, keep empty fields and put the rest in the last field.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)splits on white space.Regex.Splitsplits on a pattern. - Go.
strings.Splitandstrings.SplitNmatch the contract.SplitNwith n = 0 returns nil, so the code callsSplitfor no limit.strings.Fieldssplits on white space, andRegexp.Split(s, -1)splits on a pattern. - Rust.
s.split(sep)ands.splitn(n, sep)return iterators of slices that borrow froms.split_ascii_whitespacesplits on ASCII white space. A pattern can also be achar, a slice ofcharvalues or a closure. The standard library has no regular expressions, so the Rust solution has nosplit_regex. Theregexcrate supplies them. - C. The C function
strtokskips empty fields (see Pitfalls). So the code finds each separator withstrstr. It returns an array of fields that point into the input, and it copies no text.split_regexuses POSIXregcompandregexecwithREG_EXTENDED. - C++. A loop with
std::string_view::findreturns views into the input.std::views::splitalso splits astring_view, but it has no limit.split_regexcallsstd::regex_searchin a loop. - Bash. A loop takes the text before the first separator with
${s%%"$sep"*}and removes it with${s#*"$sep"}. The quotes make the separator literal, because a quoted pattern character matches itself.read -awithIFSset to space, tab and newline splits on runs of white space.[[ $s =~ $re ]]finds a regular expression match, and the code cuts the string at that match.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. The cases of split_whitespace and split_regex are in cases/whitespace.jsonl and cases/regex.jsonl.
empty: the empty string gives one empty field,[""], and not an empty list.split_whitespacegives[]for it.leading-separator,trailing-separatorsandadjacent-separators: each gives an empty field. Javasplitwith no limit, Cstrtokand Bashreadlose some of them.only-separator:","gives two empty fields.overlapping-match: the search goes on after the end of a match, so"aaa"on"aa"gives["", "a"].dot-separatorandpipe-separator: in a regular expression,.matches any character, and|alone matches the empty string. So a function that takes a pattern gives the wrong fields for these separators.non-ascii: the separator→is 3 bytes in UTF-8. The C, C++, Go and Rust solutions search bytes. In UTF-8 a first byte never has the form of a continuation byte, so a byte search for a whole character never matches inside another character.limit-one,limit-above-countandlimit-keeps-trailing-empty: a limit of 1 gives the whole string, and a limit above the number of fields has no effect.- An empty separator is not in the contract. Go
strings.Splitsplits after each UTF-8 sequence, and JavaScriptsplit("")splits into UTF-16 code units. Rustsplit("")also gives an empty string at the start and at the end.
Pitfalls
- Java
splittakes a regular expression and drops trailing empty strings. The.matches every character, so every field is empty, and the limit of 0 removes all of them:
This code runs but gives a wrong answer on purpose.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString("192.168.0.1".split(".")));
System.out.println(Arrays.toString("a,b,,".split(",")));
}
}
[]
[a, b]
Quote the separator, and give a negative limit:
import java.util.Arrays;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString("192.168.0.1".split(Pattern.quote("."), -1)));
System.out.println(Arrays.toString("a,b,,".split(Pattern.quote(","), -1)));
}
}
[192, 168, 0, 1]
[a, b, , ]
- The JavaScript limit drops the rest. Python, Go, Rust, Java and C# put the rest of the string in the last field. JavaScript stops when it has
limitfields and does not return the rest:
This code runs but gives a wrong answer on purpose.
console.log("key=value=more".split("=", 2));
[ 'key', 'value' ]
- Python
split()andsplit(" ")differ. With no argument, Python splits on runs of white space and drops the empty strings at the ends. With" ", each space is a separator:
text = " two words "
print(text.split())
print(text.split(" "))
['two', 'words']
['', '', 'two', '', 'words', '']
IFSsplitting in Bash drops a trailing empty field. A non-white-spaceIFScharacter ends a field, so a separator at the end does not start another field. The input has four fields, butreadgives three:
This code runs but gives a wrong answer on purpose.
IFS=, read -r -a fields <<<'a,b,,'
printf '%d fields:' "${#fields[@]}"
printf ' [%s]' "${fields[@]}"
echo
3 fields: [a] [b] []
- C
strtokskips empty fields and changes the input. It treats its second argument as a set of characters and skips a run of them. It also writes null characters into the string, and it keeps its position in a static variable, so it is not thread-safe:
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <string.h>
int main(void) {
char line[] = "a,,b,";
for (char *field = strtok(line, ","); field != NULL; field = strtok(NULL, ",")) {
printf("[%s]\n", field);
}
}
[a]
[b]
- A string literal as the C++
std::views::splitdelimiter. Aconst chararray includes its terminating null character, so the delimiter becomes", \0". That never occurs, and the result is one field:
This code runs but gives a wrong answer on purpose.
#include <print>
#include <ranges>
#include <string_view>
int main() {
std::string_view text = "a, b, c";
for (auto field : std::views::split(text, ", ")) {
std::println("[{}]", std::string_view(field));
}
}
[a, b, c]
Use a std::string_view delimiter:
#include <print>
#include <ranges>
#include <string_view>
int main() {
using namespace std::string_view_literals;
std::string_view text = "a, b, c";
for (auto field : std::views::split(text, ", "sv)) {
std::println("[{}]", std::string_view(field));
}
}
[a]
[b]
[c]
- The languages do not agree on white space. Python
split(), Gostrings.Fields, Rustsplit_whitespace, JavaScript\sand C#Char.IsWhiteSpaceuse a Unicode definition of white space. Each of them splits on U+00A0 NO-BREAK SPACE. Java\smatches only[ \t\n\x0B\f\r], unless the pattern setsUNICODE_CHARACTER_CLASSor(?U). Rustsplit_ascii_whitespaceand the C and Bash solutions also split only on ASCII characters. So the contract allows only space, tab and LF:
public class Main {
public static void main(String[] args) {
String text = "no\u00a0break";
System.out.println("fields with \\s: " + text.split("\\s+").length);
System.out.println("fields with (?U)\\s: " + text.split("(?U)\\s+").length);
}
}
fields with \s: 1
fields with (?U)\s: 2
- Capturing groups in a split pattern. Python
re.split, JavaScriptsplitand .NETRegex.Splitput the text of each capturing group in the result, between the fields. Use a non-capturing group(?:...)in a split pattern.
Related tasks
- Reverse a string: another job where bytes, code units and characters are not the same.
- Sort a list of records: sort the records after you split each line into fields.
- Read an environment variable: a value such as a list of paths needs a split.
- Parse command-line arguments: read options and file names from the argument list.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/split-a-string/.
import re
def split(s: str, sep: str, limit: int = 0) -> list[str]:
"""Split s on the literal separator sep and keep the empty fields.
With a limit n > 0 the result has at most n fields, and the last field
holds the rest of s. A limit of 0 means no limit.
"""
return s.split(sep, limit - 1 if limit > 0 else -1)
def split_whitespace(s: str) -> list[str]:
"""Split s on runs of white space. The result has no empty fields."""
return s.split()
def split_regex(s: str, pattern: str) -> list[str]:
"""Split s on each match of the regular expression pattern."""
return re.split(pattern, s)
test_split.py 68 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/split-a-string/.
import pytest
from split import split, split_regex, split_whitespace
CASES = {
"comma": ("a,b,c", ",", 0, ["a", "b", "c"]),
"csv-line": ("Ada,1815,London", ",", 0, ["Ada", "1815", "London"]),
"multi-char-separator": ("a::b::c", "::", 0, ["a", "b", "c"]),
"space-separator": ("one two three", " ", 0, ["one", "two", "", "three"]),
"limit-two": ("key=value=more", "=", 2, ["key", "value=more"]),
"empty": ("", ",", 0, [""]),
"no-separator": ("abc", ",", 0, ["abc"]),
"leading-separator": (",a,b", ",", 0, ["", "a", "b"]),
"trailing-separators": ("a,b,,", ",", 0, ["a", "b", "", ""]),
"adjacent-separators": ("a,,b", ",", 0, ["a", "", "b"]),
"only-separator": (",", ",", 0, ["", ""]),
"overlapping-match": ("aaa", "aa", 0, ["", "a"]),
"dot-separator": ("192.168.0.1", ".", 0, ["192", "168", "0", "1"]),
"pipe-separator": ("a|b|c", "|", 0, ["a", "b", "c"]),
"non-ascii": ("día→naïve→日本→🙂", "→", 0, ["día", "naïve", "日本", "🙂"]),
"limit-one": ("a,b,c", ",", 1, ["a,b,c"]),
"limit-above-count": ("a,b", ",", 5, ["a", "b"]),
"limit-keeps-trailing-empty": ("a,b,", ",", 3, ["a", "b", ""]),
}
WHITESPACE_CASES = {
"single-spaces": ("a b c", ["a", "b", "c"]),
"runs-and-ends": (" lead and trail ", ["lead", "and", "trail"]),
"tabs-and-newlines": ("a\t\tb\nc\n", ["a", "b", "c"]),
"one-word": ("word", ["word"]),
"empty": ("", []),
"only-white-space": (" \t\n ", []),
}
REGEX_CASES = {
"comma-or-semicolon": ("a, b;c ,d", "[ ]*[,;][ ]*", ["a", "b", "c", "d"]),
"digit-runs": ("a1b22c333", "[0-9]+", ["a", "b", "c", ""]),
"adjacent-matches": ("a,;b", "[,;]", ["a", "", "b"]),
"leading-and-trailing": (";a;", ";", ["", "a", ""]),
"empty": ("", "[,;]", [""]),
"no-match": ("abc", "[0-9]+", ["abc"]),
}
@pytest.mark.parametrize("name", CASES)
def test_split(name):
s, sep, limit, want = CASES[name]
assert split(s, sep, limit) == want
@pytest.mark.parametrize("name", WHITESPACE_CASES)
def test_split_whitespace(name):
s, want = WHITESPACE_CASES[name]
assert split_whitespace(s) == want
@pytest.mark.parametrize("name", REGEX_CASES)
def test_split_regex(name):
s, pattern, want = REGEX_CASES[name]
assert split_regex(s, pattern) == want
def test_empty_separator_is_an_error():
with pytest.raises(ValueError):
split("abc", "")
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
#include "split.hpp"
#include <regex>
std::vector<std::string_view> split(std::string_view s, std::string_view sep, std::size_t limit) {
std::vector<std::string_view> fields;
std::size_t start = 0;
for (std::size_t at; (limit == 0 || fields.size() + 1 < limit) &&
(at = s.find(sep, start)) != std::string_view::npos;
start = at + sep.size()) {
fields.push_back(s.substr(start, at - start));
}
fields.push_back(s.substr(start));
return fields;
}
std::vector<std::string_view> split_whitespace(std::string_view s) {
constexpr std::string_view space = " \t\n";
std::vector<std::string_view> fields;
for (std::size_t start = s.find_first_not_of(space); start != std::string_view::npos;) {
std::size_t end = s.find_first_of(space, start);
fields.push_back(s.substr(start, end - start));
start = s.find_first_not_of(space, end);
}
return fields;
}
std::vector<std::string> split_regex(const std::string& s, const std::string& pattern) {
const std::regex re(pattern);
std::vector<std::string> fields;
auto start = s.cbegin();
// std::sregex_token_iterator with -1 drops a trailing empty field, so the
// loop calls std::regex_search itself.
for (std::smatch m; std::regex_search(start, s.cend(), m, re) && m.length(0) > 0;
start = m[0].second) {
fields.emplace_back(start, m[0].first);
}
fields.emplace_back(start, s.cend());
return fields;
}
split.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
#include <vector>
// Splits s on the literal separator sep, which must not be empty, and keeps
// the empty fields. With limit n > 0 there are at most n fields, and the last
// field holds the rest of s. A limit of 0 means no limit. The fields are views
// into s, so s must live longer than the result.
std::vector<std::string_view> split(std::string_view s, std::string_view sep, std::size_t limit = 0);
// Splits s on runs of space, tab and LF. There are no empty fields.
std::vector<std::string_view> split_whitespace(std::string_view s);
// Splits s on each match of the ECMAScript regular expression pattern, which
// must not match the empty string. Throws std::regex_error for a bad pattern.
std::vector<std::string> split_regex(const std::string& s, const std::string& pattern);
test_split.cpp 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
#include <cstdio>
#include <regex>
#include <string>
#include <string_view>
#include <vector>
#include "split.hpp"
namespace {
int failures = 0;
void check(std::string_view name, bool ok) {
if (!ok) {
std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(name.size()), name.data());
++failures;
}
}
} // namespace
int main() {
using List = std::vector<std::string_view>;
struct Case {
std::string_view name, s, sep;
std::size_t limit;
List want;
};
const std::vector<Case> cases = {
{"comma", "a,b,c", ",", 0, {"a", "b", "c"}},
{"csv-line", "Ada,1815,London", ",", 0, {"Ada", "1815", "London"}},
{"multi-char-separator", "a::b::c", "::", 0, {"a", "b", "c"}},
{"space-separator", "one two three", " ", 0, {"one", "two", "", "three"}},
{"limit-two", "key=value=more", "=", 2, {"key", "value=more"}},
{"empty", "", ",", 0, {""}},
{"no-separator", "abc", ",", 0, {"abc"}},
{"leading-separator", ",a,b", ",", 0, {"", "a", "b"}},
{"trailing-separators", "a,b,,", ",", 0, {"a", "b", "", ""}},
{"adjacent-separators", "a,,b", ",", 0, {"a", "", "b"}},
{"only-separator", ",", ",", 0, {"", ""}},
{"overlapping-match", "aaa", "aa", 0, {"", "a"}},
{"dot-separator", "192.168.0.1", ".", 0, {"192", "168", "0", "1"}},
{"pipe-separator", "a|b|c", "|", 0, {"a", "b", "c"}},
{"non-ascii", "día→naïve→日本→🙂", "→", 0, {"día", "naïve", "日本", "🙂"}},
{"limit-one", "a,b,c", ",", 1, {"a,b,c"}},
{"limit-above-count", "a,b", ",", 5, {"a", "b"}},
{"limit-keeps-trailing-empty", "a,b,", ",", 3, {"a", "b", ""}},
};
for (const auto& c : cases) {
check(c.name, split(c.s, c.sep, c.limit) == c.want);
}
struct WhitespaceCase {
std::string_view name, s;
List want;
};
const std::vector<WhitespaceCase> whitespace_cases = {
{"single-spaces", "a b c", {"a", "b", "c"}},
{"runs-and-ends", " lead and trail ", {"lead", "and", "trail"}},
{"tabs-and-newlines", "a\t\tb\nc\n", {"a", "b", "c"}},
{"one-word", "word", {"word"}},
{"empty", "", {}},
{"only-white-space", " \t\n ", {}},
};
for (const auto& c : whitespace_cases) {
check(c.name, split_whitespace(c.s) == c.want);
}
struct RegexCase {
std::string_view name;
std::string s, pattern;
std::vector<std::string> want;
};
const std::vector<RegexCase> regex_cases = {
{"comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", {"a", "b", "c", "d"}},
{"digit-runs", "a1b22c333", "[0-9]+", {"a", "b", "c", ""}},
{"adjacent-matches", "a,;b", "[,;]", {"a", "", "b"}},
{"leading-and-trailing", ";a;", ";", {"", "a", ""}},
{"empty", "", "[,;]", {""}},
{"no-match", "abc", "[0-9]+", {"abc"}},
};
for (const auto& c : regex_cases) {
check(c.name, split_regex(c.s, c.pattern) == c.want);
}
bool threw = false;
try {
split_regex("a", "[a");
} catch (const std::regex_error&) {
threw = true;
}
check("bad-pattern", threw);
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/** Splits strings on a literal separator, on white space and on a regular expression. */
public final class Split {
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
private Split() {}
/**
* Splits s on the literal separator sep and keeps the empty fields. With a limit n > 0 the
* result has at most n fields, and the last field holds the rest of s. A limit of 0 means no
* limit.
*/
public static List<String> split(String s, String sep, int limit) {
// String.split takes a regular expression, so quote the separator. A negative limit keeps
// the trailing empty strings, which a limit of 0 removes.
return List.of(s.split(Pattern.quote(sep), limit > 0 ? limit : -1));
}
/** Splits s on runs of white space. The result has no empty fields. */
public static List<String> splitWhitespace(String s) {
return Arrays.stream(WHITESPACE.split(s)).filter(field -> !field.isEmpty()).toList();
}
/** Splits s on each match of the regular expression pattern. */
public static List<String> splitRegex(String s, String pattern) {
return List.of(Pattern.compile(pattern).split(s, -1));
}
}
SplitTest.java 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class SplitTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("comma", "a,b,c", ",", 0, List.of("a", "b", "c")),
Arguments.of("csv-line", "Ada,1815,London", ",", 0, List.of("Ada", "1815", "London")),
Arguments.of("multi-char-separator", "a::b::c", "::", 0, List.of("a", "b", "c")),
Arguments.of("space-separator", "one two three", " ", 0, List.of("one", "two", "", "three")),
Arguments.of("limit-two", "key=value=more", "=", 2, List.of("key", "value=more")),
Arguments.of("empty", "", ",", 0, List.of("")),
Arguments.of("no-separator", "abc", ",", 0, List.of("abc")),
Arguments.of("leading-separator", ",a,b", ",", 0, List.of("", "a", "b")),
Arguments.of("trailing-separators", "a,b,,", ",", 0, List.of("a", "b", "", "")),
Arguments.of("adjacent-separators", "a,,b", ",", 0, List.of("a", "", "b")),
Arguments.of("only-separator", ",", ",", 0, List.of("", "")),
Arguments.of("overlapping-match", "aaa", "aa", 0, List.of("", "a")),
Arguments.of("dot-separator", "192.168.0.1", ".", 0, List.of("192", "168", "0", "1")),
Arguments.of("pipe-separator", "a|b|c", "|", 0, List.of("a", "b", "c")),
Arguments.of("non-ascii", "día→naïve→日本→🙂", "→", 0, List.of("día", "naïve", "日本", "🙂")),
Arguments.of("limit-one", "a,b,c", ",", 1, List.of("a,b,c")),
Arguments.of("limit-above-count", "a,b", ",", 5, List.of("a", "b")),
Arguments.of("limit-keeps-trailing-empty", "a,b,", ",", 3, List.of("a", "b", "")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void split(String name, String s, String sep, int limit, List<String> want) {
assertEquals(want, Split.split(s, sep, limit));
}
static Stream<Arguments> whitespaceCases() {
return Stream.of(
Arguments.of("single-spaces", "a b c", List.of("a", "b", "c")),
Arguments.of("runs-and-ends", " lead and trail ", List.of("lead", "and", "trail")),
Arguments.of("tabs-and-newlines", "a\t\tb\nc\n", List.of("a", "b", "c")),
Arguments.of("one-word", "word", List.of("word")),
Arguments.of("empty", "", List.of()),
Arguments.of("only-white-space", " \t\n ", List.of()));
}
@ParameterizedTest(name = "{0}")
@MethodSource("whitespaceCases")
void splitWhitespace(String name, String s, List<String> want) {
assertEquals(want, Split.splitWhitespace(s));
}
static Stream<Arguments> regexCases() {
return Stream.of(
Arguments.of("comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", List.of("a", "b", "c", "d")),
Arguments.of("digit-runs", "a1b22c333", "[0-9]+", List.of("a", "b", "c", "")),
Arguments.of("adjacent-matches", "a,;b", "[,;]", List.of("a", "", "b")),
Arguments.of("leading-and-trailing", ";a;", ";", List.of("", "a", "")),
Arguments.of("empty", "", "[,;]", List.of("")),
Arguments.of("no-match", "abc", "[0-9]+", List.of("abc")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("regexCases")
void splitRegex(String name, String s, String pattern, List<String> want) {
assertEquals(want, Split.splitRegex(s, pattern));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
#define _POSIX_C_SOURCE 200809L
#include "split.h"
#include <regex.h>
#include <stdlib.h>
#include <string.h>
// push appends a field to the array *fields of *count elements, which has
// room for *cap. It returns 0, or -1 if there is no memory.
static int push(struct field **fields, size_t *count, size_t *cap, const char *start, size_t len) {
if (*count == *cap) {
size_t n = *cap == 0 ? 8 : *cap * 2;
struct field *p = realloc(*fields, n * sizeof **fields);
if (p == NULL) {
return -1;
}
*fields = p;
*cap = n;
}
(*fields)[(*count)++] = (struct field){start, len};
return 0;
}
struct field *split(const char *s, const char *sep, size_t limit, size_t *count) {
struct field *fields = NULL;
size_t n = 0, cap = 0, seplen = strlen(sep);
const char *at;
// strstr finds the next occurrence. The search goes on after its end, so
// the occurrences do not overlap.
while ((limit == 0 || n + 1 < limit) && (at = strstr(s, sep)) != NULL) {
if (push(&fields, &n, &cap, s, (size_t)(at - s)) != 0) {
free(fields);
return NULL;
}
s = at + seplen;
}
if (push(&fields, &n, &cap, s, strlen(s)) != 0) {
free(fields);
return NULL;
}
*count = n;
return fields;
}
struct field *split_whitespace(const char *s, size_t *count) {
static const char space[] = " \t\n";
struct field *fields = malloc(sizeof *fields);
size_t n = 0, cap = 1;
if (fields == NULL) {
return NULL;
}
for (;;) {
s += strspn(s, space);
if (*s == '\0') {
break;
}
size_t len = strcspn(s, space);
if (push(&fields, &n, &cap, s, len) != 0) {
free(fields);
return NULL;
}
s += len;
}
*count = n;
return fields;
}
struct field *split_regex(const char *s, const char *pattern, size_t *count) {
regex_t re;
if (regcomp(&re, pattern, REG_EXTENDED) != 0) {
return NULL;
}
struct field *fields = NULL;
size_t n = 0, cap = 0;
regmatch_t m;
int flags = 0;
// After the first match, the rest of s does not start at a line start, so
// REG_NOTBOL stops a ^ in the pattern from matching there.
while (regexec(&re, s, 1, &m, flags) == 0 && m.rm_eo > m.rm_so) {
if (push(&fields, &n, &cap, s, (size_t)m.rm_so) != 0) {
goto fail;
}
s += m.rm_eo;
flags = REG_NOTBOL;
}
if (push(&fields, &n, &cap, s, strlen(s)) != 0) {
goto fail;
}
regfree(&re);
*count = n;
return fields;
fail:
regfree(&re);
free(fields);
return NULL;
}
split.h 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
#ifndef SPLIT_H
#define SPLIT_H
#include <stddef.h>
// A field is a part of the input string. It is not a copy, and it has no
// terminating null character.
struct field {
const char *start;
size_t len;
};
// split splits s on the literal separator sep, which must not be empty, and
// keeps the empty fields. With limit n > 0 there are at most n fields, and the
// last field holds the rest of s. A limit of 0 means no limit. It stores the
// number of fields in *count and returns an array that the caller frees with
// free, or NULL if there is no memory.
struct field *split(const char *s, const char *sep, size_t limit, size_t *count);
// split_whitespace splits s on runs of space, tab and LF. There are no empty
// fields, so a string of only white space gives a count of 0.
struct field *split_whitespace(const char *s, size_t *count);
// split_regex splits s on each match of the POSIX extended regular expression
// pattern, which must not match the empty string. It returns NULL if the
// pattern is not valid or if there is no memory.
struct field *split_regex(const char *s, const char *pattern, size_t *count);
#endif
test_split.c 92 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
#include "split.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
// check compares the fields with want, an array of strings that ends with NULL.
static void check(const char *name, struct field *got, size_t count, const char *const *want) {
size_t i = 0;
int ok = got != NULL;
for (; ok && want[i] != NULL; i++) {
ok = i < count && got[i].len == strlen(want[i]) &&
memcmp(got[i].start, want[i], got[i].len) == 0;
}
if (!ok || i != count) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
free(got);
}
// Each macro calls the split function before check, because C does not fix the order in which the arguments of a call are evaluated, and check reads n.
#define WANT(...) ((const char *const[]){__VA_ARGS__, NULL})
#define NONE ((const char *const[]){NULL})
#define SPLIT(name, s, sep, limit, want) \
do { \
size_t n = 0; \
struct field *got = split(s, sep, limit, &n); \
check(name, got, n, want); \
} while (0)
#define SPLIT_WS(name, s, want) \
do { \
size_t n = 0; \
struct field *got = split_whitespace(s, &n); \
check(name, got, n, want); \
} while (0)
#define SPLIT_RE(name, s, pattern, want) \
do { \
size_t n = 0; \
struct field *got = split_regex(s, pattern, &n); \
check(name, got, n, want); \
} while (0)
int main(void) {
SPLIT("comma", "a,b,c", ",", 0, WANT("a", "b", "c"));
SPLIT("csv-line", "Ada,1815,London", ",", 0, WANT("Ada", "1815", "London"));
SPLIT("multi-char-separator", "a::b::c", "::", 0, WANT("a", "b", "c"));
SPLIT("space-separator", "one two three", " ", 0, WANT("one", "two", "", "three"));
SPLIT("limit-two", "key=value=more", "=", 2, WANT("key", "value=more"));
SPLIT("empty", "", ",", 0, WANT(""));
SPLIT("no-separator", "abc", ",", 0, WANT("abc"));
SPLIT("leading-separator", ",a,b", ",", 0, WANT("", "a", "b"));
SPLIT("trailing-separators", "a,b,,", ",", 0, WANT("a", "b", "", ""));
SPLIT("adjacent-separators", "a,,b", ",", 0, WANT("a", "", "b"));
SPLIT("only-separator", ",", ",", 0, WANT("", ""));
SPLIT("overlapping-match", "aaa", "aa", 0, WANT("", "a"));
SPLIT("dot-separator", "192.168.0.1", ".", 0, WANT("192", "168", "0", "1"));
SPLIT("pipe-separator", "a|b|c", "|", 0, WANT("a", "b", "c"));
SPLIT("non-ascii", "día→naïve→日本→🙂", "→", 0, WANT("día", "naïve", "日本", "🙂"));
SPLIT("limit-one", "a,b,c", ",", 1, WANT("a,b,c"));
SPLIT("limit-above-count", "a,b", ",", 5, WANT("a", "b"));
SPLIT("limit-keeps-trailing-empty", "a,b,", ",", 3, WANT("a", "b", ""));
SPLIT_WS("single-spaces", "a b c", WANT("a", "b", "c"));
SPLIT_WS("runs-and-ends", " lead and trail ", WANT("lead", "and", "trail"));
SPLIT_WS("tabs-and-newlines", "a\t\tb\nc\n", WANT("a", "b", "c"));
SPLIT_WS("one-word", "word", WANT("word"));
SPLIT_WS("empty", "", NONE);
SPLIT_WS("only-white-space", " \t\n ", NONE);
SPLIT_RE("comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", WANT("a", "b", "c", "d"));
SPLIT_RE("digit-runs", "a1b22c333", "[0-9]+", WANT("a", "b", "c", ""));
SPLIT_RE("adjacent-matches", "a,;b", "[,;]", WANT("a", "", "b"));
SPLIT_RE("leading-and-trailing", ";a;", ";", WANT("", "a", ""));
SPLIT_RE("empty", "", "[,;]", WANT(""));
SPLIT_RE("no-match", "abc", "[0-9]+", WANT("abc"));
size_t n;
if (split_regex("a", "[a", &n) != NULL) {
fprintf(stderr, "bad pattern: no error\n");
failures++;
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
using System.Text.RegularExpressions;
/// <summary>Splits strings on a literal separator, on white space and on a regular expression.</summary>
public static class Splitter
{
/// <summary>
/// Splits s on the literal separator sep and keeps the empty fields. With a limit n > 0
/// the result has at most n fields, and the last field holds the rest of s. A limit of 0
/// means no limit.
/// </summary>
public static string[] Split(string s, string sep, int limit = 0) =>
limit > 0 ? s.Split(sep, limit) : s.Split(sep);
/// <summary>Splits s on runs of white space. The result has no empty fields.</summary>
public static string[] SplitWhitespace(string s) =>
s.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
/// <summary>Splits s on each match of the regular expression pattern.</summary>
public static string[] SplitRegex(string s, string pattern) => Regex.Split(s, pattern);
}
SplitTests.cs 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
using Xunit;
public sealed class SplitTests
{
public static TheoryData<string, string, string, int, string[]> Cases => new()
{
{ "comma", "a,b,c", ",", 0, ["a", "b", "c"] },
{ "csv-line", "Ada,1815,London", ",", 0, ["Ada", "1815", "London"] },
{ "multi-char-separator", "a::b::c", "::", 0, ["a", "b", "c"] },
{ "space-separator", "one two three", " ", 0, ["one", "two", "", "three"] },
{ "limit-two", "key=value=more", "=", 2, ["key", "value=more"] },
{ "empty", "", ",", 0, [""] },
{ "no-separator", "abc", ",", 0, ["abc"] },
{ "leading-separator", ",a,b", ",", 0, ["", "a", "b"] },
{ "trailing-separators", "a,b,,", ",", 0, ["a", "b", "", ""] },
{ "adjacent-separators", "a,,b", ",", 0, ["a", "", "b"] },
{ "only-separator", ",", ",", 0, ["", ""] },
{ "overlapping-match", "aaa", "aa", 0, ["", "a"] },
{ "dot-separator", "192.168.0.1", ".", 0, ["192", "168", "0", "1"] },
{ "pipe-separator", "a|b|c", "|", 0, ["a", "b", "c"] },
{ "non-ascii", "día→naïve→日本→🙂", "→", 0, ["día", "naïve", "日本", "🙂"] },
{ "limit-one", "a,b,c", ",", 1, ["a,b,c"] },
{ "limit-above-count", "a,b", ",", 5, ["a", "b"] },
{ "limit-keeps-trailing-empty", "a,b,", ",", 3, ["a", "b", ""] },
};
[Theory]
[MemberData(nameof(Cases))]
public void Split(string name, string s, string sep, int limit, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Splitter.Split(s, sep, limit));
}
public static TheoryData<string, string, string[]> WhitespaceCases => new()
{
{ "single-spaces", "a b c", ["a", "b", "c"] },
{ "runs-and-ends", " lead and trail ", ["lead", "and", "trail"] },
{ "tabs-and-newlines", "a\t\tb\nc\n", ["a", "b", "c"] },
{ "one-word", "word", ["word"] },
{ "empty", "", [] },
{ "only-white-space", " \t\n ", [] },
};
[Theory]
[MemberData(nameof(WhitespaceCases))]
public void SplitWhitespace(string name, string s, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Splitter.SplitWhitespace(s));
}
public static TheoryData<string, string, string, string[]> RegexCases => new()
{
{ "comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", ["a", "b", "c", "d"] },
{ "digit-runs", "a1b22c333", "[0-9]+", ["a", "b", "c", ""] },
{ "adjacent-matches", "a,;b", "[,;]", ["a", "", "b"] },
{ "leading-and-trailing", ";a;", ";", ["", "a", ""] },
{ "empty", "", "[,;]", [""] },
{ "no-match", "abc", "[0-9]+", ["abc"] },
};
[Theory]
[MemberData(nameof(RegexCases))]
public void SplitRegex(string name, string s, string pattern, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Splitter.SplitRegex(s, pattern));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
/**
* Splits s on the literal separator sep and keeps the empty fields. With a
* limit n > 0 the result has at most n fields, and the last field holds the
* rest of s. A limit of 0 means no limit.
*/
export function split(s, sep, limit = 0) {
const fields = s.split(sep);
if (limit === 0 || fields.length <= limit) {
return fields;
}
// The limit argument of String.prototype.split drops the rest, so join it.
return [...fields.slice(0, limit - 1), fields.slice(limit - 1).join(sep)];
}
/** Splits s on runs of white space. The result has no empty fields. */
export function splitWhitespace(s) {
return s.split(/\s+/).filter((field) => field !== "");
}
/** Splits s on each match of the regular expression pattern. */
export function splitRegex(s, pattern) {
return s.split(new RegExp(pattern, "u"));
}
split.test.js 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { split, splitRegex, splitWhitespace } from "./split.js";
const cases = [
["comma", "a,b,c", ",", 0, ["a", "b", "c"]],
["csv-line", "Ada,1815,London", ",", 0, ["Ada", "1815", "London"]],
["multi-char-separator", "a::b::c", "::", 0, ["a", "b", "c"]],
["space-separator", "one two three", " ", 0, ["one", "two", "", "three"]],
["limit-two", "key=value=more", "=", 2, ["key", "value=more"]],
["empty", "", ",", 0, [""]],
["no-separator", "abc", ",", 0, ["abc"]],
["leading-separator", ",a,b", ",", 0, ["", "a", "b"]],
["trailing-separators", "a,b,,", ",", 0, ["a", "b", "", ""]],
["adjacent-separators", "a,,b", ",", 0, ["a", "", "b"]],
["only-separator", ",", ",", 0, ["", ""]],
["overlapping-match", "aaa", "aa", 0, ["", "a"]],
["dot-separator", "192.168.0.1", ".", 0, ["192", "168", "0", "1"]],
["pipe-separator", "a|b|c", "|", 0, ["a", "b", "c"]],
["non-ascii", "día→naïve→日本→🙂", "→", 0, ["día", "naïve", "日本", "🙂"]],
["limit-one", "a,b,c", ",", 1, ["a,b,c"]],
["limit-above-count", "a,b", ",", 5, ["a", "b"]],
["limit-keeps-trailing-empty", "a,b,", ",", 3, ["a", "b", ""]],
];
for (const [name, s, sep, limit, want] of cases) {
test(name, () => assert.deepEqual(split(s, sep, limit), want));
}
const whitespaceCases = [
["single-spaces", "a b c", ["a", "b", "c"]],
["runs-and-ends", " lead and trail ", ["lead", "and", "trail"]],
["tabs-and-newlines", "a\t\tb\nc\n", ["a", "b", "c"]],
["one-word", "word", ["word"]],
["empty", "", []],
["only-white-space", " \t\n ", []],
];
for (const [name, s, want] of whitespaceCases) {
test(`whitespace ${name}`, () => assert.deepEqual(splitWhitespace(s), want));
}
const regexCases = [
["comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", ["a", "b", "c", "d"]],
["digit-runs", "a1b22c333", "[0-9]+", ["a", "b", "c", ""]],
["adjacent-matches", "a,;b", "[,;]", ["a", "", "b"]],
["leading-and-trailing", ";a;", ";", ["", "a", ""]],
["empty", "", "[,;]", [""]],
["no-match", "abc", "[0-9]+", ["abc"]],
];
for (const [name, s, pattern, want] of regexCases) {
test(`regex ${name}`, () => assert.deepEqual(splitRegex(s, pattern), want));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
/**
* Splits s on the literal separator sep and keeps the empty fields. With a
* limit n > 0 the result has at most n fields, and the last field holds the
* rest of s. A limit of 0 means no limit.
*/
export function split(s: string, sep: string, limit = 0): string[] {
const fields = s.split(sep);
if (limit === 0 || fields.length <= limit) {
return fields;
}
// The limit argument of String.prototype.split drops the rest, so join it.
return [...fields.slice(0, limit - 1), fields.slice(limit - 1).join(sep)];
}
/** Splits s on runs of white space. The result has no empty fields. */
export function splitWhitespace(s: string): string[] {
return s.split(/\s+/).filter((field) => field !== "");
}
/** Splits s on each match of the regular expression pattern. */
export function splitRegex(s: string, pattern: string): string[] {
return s.split(new RegExp(pattern, "u"));
}
split.test.ts 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { split, splitRegex, splitWhitespace } from "./split.ts";
const cases: [string, string, string, number, string[]][] = [
["comma", "a,b,c", ",", 0, ["a", "b", "c"]],
["csv-line", "Ada,1815,London", ",", 0, ["Ada", "1815", "London"]],
["multi-char-separator", "a::b::c", "::", 0, ["a", "b", "c"]],
["space-separator", "one two three", " ", 0, ["one", "two", "", "three"]],
["limit-two", "key=value=more", "=", 2, ["key", "value=more"]],
["empty", "", ",", 0, [""]],
["no-separator", "abc", ",", 0, ["abc"]],
["leading-separator", ",a,b", ",", 0, ["", "a", "b"]],
["trailing-separators", "a,b,,", ",", 0, ["a", "b", "", ""]],
["adjacent-separators", "a,,b", ",", 0, ["a", "", "b"]],
["only-separator", ",", ",", 0, ["", ""]],
["overlapping-match", "aaa", "aa", 0, ["", "a"]],
["dot-separator", "192.168.0.1", ".", 0, ["192", "168", "0", "1"]],
["pipe-separator", "a|b|c", "|", 0, ["a", "b", "c"]],
["non-ascii", "día→naïve→日本→🙂", "→", 0, ["día", "naïve", "日本", "🙂"]],
["limit-one", "a,b,c", ",", 1, ["a,b,c"]],
["limit-above-count", "a,b", ",", 5, ["a", "b"]],
["limit-keeps-trailing-empty", "a,b,", ",", 3, ["a", "b", ""]],
];
for (const [name, s, sep, limit, want] of cases) {
test(name, () => assert.deepEqual(split(s, sep, limit), want));
}
const whitespaceCases: [string, string, string[]][] = [
["single-spaces", "a b c", ["a", "b", "c"]],
["runs-and-ends", " lead and trail ", ["lead", "and", "trail"]],
["tabs-and-newlines", "a\t\tb\nc\n", ["a", "b", "c"]],
["one-word", "word", ["word"]],
["empty", "", []],
["only-white-space", " \t\n ", []],
];
for (const [name, s, want] of whitespaceCases) {
test(`whitespace ${name}`, () => assert.deepEqual(splitWhitespace(s), want));
}
const regexCases: [string, string, string, string[]][] = [
["comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", ["a", "b", "c", "d"]],
["digit-runs", "a1b22c333", "[0-9]+", ["a", "b", "c", ""]],
["adjacent-matches", "a,;b", "[,;]", ["a", "", "b"]],
["leading-and-trailing", ";a;", ";", ["", "a", ""]],
["empty", "", "[,;]", [""]],
["no-match", "abc", "[0-9]+", ["abc"]],
];
for (const [name, s, pattern, want] of regexCases) {
test(`regex ${name}`, () => assert.deepEqual(splitRegex(s, pattern), want));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
// Package split splits strings on a literal separator, on white space and on
// a regular expression.
package split
import (
"regexp"
"strings"
)
// Split splits s on the literal separator sep and keeps the empty fields.
// With limit n > 0 the result has at most n fields, and the last field holds
// the rest of s. A limit of 0 means no limit.
func Split(s, sep string, limit int) []string {
if limit == 0 {
return strings.Split(s, sep)
}
return strings.SplitN(s, sep, limit)
}
// SplitWhitespace splits s on runs of white space. The result has no empty
// fields.
func SplitWhitespace(s string) []string {
return strings.Fields(s)
}
// SplitRegex splits s on each match of the regular expression pattern.
func SplitRegex(s, pattern string) ([]string, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return re.Split(s, -1), nil
}
split_test.go 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
package split
import (
"slices"
"testing"
)
func TestSplit(t *testing.T) {
cases := []struct {
name, s, sep string
limit int
want []string
}{
{"comma", "a,b,c", ",", 0, []string{"a", "b", "c"}},
{"csv-line", "Ada,1815,London", ",", 0, []string{"Ada", "1815", "London"}},
{"multi-char-separator", "a::b::c", "::", 0, []string{"a", "b", "c"}},
{"space-separator", "one two three", " ", 0, []string{"one", "two", "", "three"}},
{"limit-two", "key=value=more", "=", 2, []string{"key", "value=more"}},
{"empty", "", ",", 0, []string{""}},
{"no-separator", "abc", ",", 0, []string{"abc"}},
{"leading-separator", ",a,b", ",", 0, []string{"", "a", "b"}},
{"trailing-separators", "a,b,,", ",", 0, []string{"a", "b", "", ""}},
{"adjacent-separators", "a,,b", ",", 0, []string{"a", "", "b"}},
{"only-separator", ",", ",", 0, []string{"", ""}},
{"overlapping-match", "aaa", "aa", 0, []string{"", "a"}},
{"dot-separator", "192.168.0.1", ".", 0, []string{"192", "168", "0", "1"}},
{"pipe-separator", "a|b|c", "|", 0, []string{"a", "b", "c"}},
{"non-ascii", "día→naïve→日本→🙂", "→", 0, []string{"día", "naïve", "日本", "🙂"}},
{"limit-one", "a,b,c", ",", 1, []string{"a,b,c"}},
{"limit-above-count", "a,b", ",", 5, []string{"a", "b"}},
{"limit-keeps-trailing-empty", "a,b,", ",", 3, []string{"a", "b", ""}},
}
for _, c := range cases {
if got := Split(c.s, c.sep, c.limit); !slices.Equal(got, c.want) {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestSplitWhitespace(t *testing.T) {
cases := []struct {
name, s string
want []string
}{
{"single-spaces", "a b c", []string{"a", "b", "c"}},
{"runs-and-ends", " lead and trail ", []string{"lead", "and", "trail"}},
{"tabs-and-newlines", "a\t\tb\nc\n", []string{"a", "b", "c"}},
{"one-word", "word", []string{"word"}},
{"empty", "", []string{}},
{"only-white-space", " \t\n ", []string{}},
}
for _, c := range cases {
if got := SplitWhitespace(c.s); !slices.Equal(got, c.want) {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestSplitRegex(t *testing.T) {
cases := []struct {
name, s, pattern string
want []string
}{
{"comma-or-semicolon", "a, b;c ,d", "[ ]*[,;][ ]*", []string{"a", "b", "c", "d"}},
{"digit-runs", "a1b22c333", "[0-9]+", []string{"a", "b", "c", ""}},
{"adjacent-matches", "a,;b", "[,;]", []string{"a", "", "b"}},
{"leading-and-trailing", ";a;", ";", []string{"", "a", ""}},
{"empty", "", "[,;]", []string{""}},
{"no-match", "abc", "[0-9]+", []string{"abc"}},
}
for _, c := range cases {
got, err := SplitRegex(c.s, c.pattern)
if err != nil || !slices.Equal(got, c.want) {
t.Errorf("%s: got %q, %v, want %q", c.name, got, err, c.want)
}
}
if _, err := SplitRegex("a", "[a"); err == nil {
t.Error("bad pattern: no error")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
//! Split a string on a literal separator and on white space. The standard
//! library has no regular expressions, so there is no `split_regex` here.
/// Splits `s` on the literal separator `sep` and keeps the empty fields.
/// With `limit` n > 0 the result has at most n fields, and the last field
/// holds the rest of `s`. A limit of 0 means no limit.
pub fn split<'a>(s: &'a str, sep: &str, limit: usize) -> Vec<&'a str> {
if limit == 0 {
s.split(sep).collect()
} else {
s.splitn(limit, sep).collect()
}
}
/// Splits `s` on runs of ASCII white space. The result has no empty fields.
pub fn split_whitespace(s: &str) -> Vec<&str> {
s.split_ascii_whitespace().collect()
}
tests/split_test.rs 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/split-a-string/.
use algo_split_a_string::{split, split_whitespace};
#[test]
fn split_cases() {
let cases: &[(&str, &str, &str, usize, &[&str])] = &[
("comma", "a,b,c", ",", 0, &["a", "b", "c"]),
("csv-line", "Ada,1815,London", ",", 0, &["Ada", "1815", "London"]),
("multi-char-separator", "a::b::c", "::", 0, &["a", "b", "c"]),
("space-separator", "one two three", " ", 0, &["one", "two", "", "three"]),
("limit-two", "key=value=more", "=", 2, &["key", "value=more"]),
("empty", "", ",", 0, &[""]),
("no-separator", "abc", ",", 0, &["abc"]),
("leading-separator", ",a,b", ",", 0, &["", "a", "b"]),
("trailing-separators", "a,b,,", ",", 0, &["a", "b", "", ""]),
("adjacent-separators", "a,,b", ",", 0, &["a", "", "b"]),
("only-separator", ",", ",", 0, &["", ""]),
("overlapping-match", "aaa", "aa", 0, &["", "a"]),
("dot-separator", "192.168.0.1", ".", 0, &["192", "168", "0", "1"]),
("pipe-separator", "a|b|c", "|", 0, &["a", "b", "c"]),
("non-ascii", "día→naïve→日本→🙂", "→", 0, &["día", "naïve", "日本", "🙂"]),
("limit-one", "a,b,c", ",", 1, &["a,b,c"]),
("limit-above-count", "a,b", ",", 5, &["a", "b"]),
("limit-keeps-trailing-empty", "a,b,", ",", 3, &["a", "b", ""]),
];
for &(name, s, sep, limit, want) in cases {
assert_eq!(split(s, sep, limit), want, "case {name}");
}
}
#[test]
fn split_whitespace_cases() {
let cases: &[(&str, &str, &[&str])] = &[
("single-spaces", "a b c", &["a", "b", "c"]),
("runs-and-ends", " lead and trail ", &["lead", "and", "trail"]),
("tabs-and-newlines", "a\t\tb\nc\n", &["a", "b", "c"]),
("one-word", "word", &["word"]),
("empty", "", &[]),
("only-white-space", " \t\n ", &[]),
];
for &(name, s, want) in cases {
assert_eq!(split_whitespace(s), want, "case {name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/split-a-string/.
# split_string S SEP [LIMIT]: splits S on the literal separator SEP, which must not
# be empty, and keeps the empty fields. With LIMIT n > 0 there are at most n
# fields, and the last field holds the rest of S. The fields go into the
# global array FIELDS.
split_string() {
local s=$1 sep=$2 limit=${3:-0}
FIELDS=()
# The quotes around $sep make it a literal string, not a pattern.
while [[ $s == *"$sep"* ]] && ((limit == 0 || ${#FIELDS[@]} + 1 < limit)); do
FIELDS+=("${s%%"$sep"*}")
s=${s#*"$sep"}
done
FIELDS+=("$s")
}
# split_whitespace S: splits S on runs of space, tab and LF. There are no
# empty fields. The fields go into the global array FIELDS.
split_whitespace() {
FIELDS=()
# read returns 1 at the end of the input, but it still fills the array.
IFS=$' \t\n' read -r -d '' -a FIELDS <<<"$1" || true
}
# split_regex S PATTERN: splits S on each match of the POSIX extended regular
# expression PATTERN, which must not match the empty string. The fields go
# into the global array FIELDS.
split_regex() {
local s=$1 re=$2 match
FIELDS=()
while [[ $s =~ $re ]] && [[ -n ${BASH_REMATCH[0]} ]]; do
match=${BASH_REMATCH[0]}
# The first copy of the matched text is the leftmost match.
FIELDS+=("${s%%"$match"*}")
s=${s#*"$match"}
done
FIELDS+=("$s")
}
test_split.bats 57 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/split-a-string/.
setup() {
source "$BATS_TEST_DIRNAME/split.sh"
}
# expect FIELD...: checks that FIELDS holds exactly the given fields.
expect() {
local want=("$@")
if [[ ${#FIELDS[@]} -ne ${#want[@]} ]]; then
echo "got ${#FIELDS[@]} fields: $(declare -p FIELDS)" >&2
return 1
fi
local i
for i in "${!want[@]}"; do
if [[ ${FIELDS[i]} != "${want[i]}" ]]; then
echo "field $i: got '${FIELDS[i]}', want '${want[i]}'" >&2
return 1
fi
done
}
@test "comma" { split_string 'a,b,c' ',' 0; expect a b c; }
@test "csv-line" { split_string 'Ada,1815,London' ',' 0; expect Ada 1815 London; }
@test "multi-char-separator" { split_string 'a::b::c' '::' 0; expect a b c; }
@test "space-separator" { split_string 'one two three' ' ' 0; expect one two '' three; }
@test "limit-two" { split_string 'key=value=more' '=' 2; expect key value=more; }
@test "empty" { split_string '' ',' 0; expect ''; }
@test "no-separator" { split_string 'abc' ',' 0; expect abc; }
@test "leading-separator" { split_string ',a,b' ',' 0; expect '' a b; }
@test "trailing-separators" { split_string 'a,b,,' ',' 0; expect a b '' ''; }
@test "adjacent-separators" { split_string 'a,,b' ',' 0; expect a '' b; }
@test "only-separator" { split_string ',' ',' 0; expect '' ''; }
@test "overlapping-match" { split_string 'aaa' 'aa' 0; expect '' a; }
@test "dot-separator" { split_string '192.168.0.1' '.' 0; expect 192 168 0 1; }
@test "pipe-separator" { split_string 'a|b|c' '|' 0; expect a b c; }
@test "non-ascii" { split_string 'día→naïve→日本→🙂' '→' 0; expect día naïve 日本 🙂; }
@test "limit-one" { split_string 'a,b,c' ',' 1; expect a,b,c; }
@test "limit-above-count" { split_string 'a,b' ',' 5; expect a b; }
@test "limit-keeps-trailing-empty" { split_string 'a,b,' ',' 3; expect a b ''; }
@test "glob characters are literal" { split_string 'a*b?c' '*' 0; expect a 'b?c'; }
@test "whitespace single-spaces" { split_whitespace 'a b c'; expect a b c; }
@test "whitespace runs-and-ends" { split_whitespace ' lead and trail '; expect lead and trail; }
@test "whitespace tabs-and-newlines" { split_whitespace $'a\t\tb\nc\n'; expect a b c; }
@test "whitespace one-word" { split_whitespace 'word'; expect word; }
@test "whitespace empty" { split_whitespace ''; expect; }
@test "whitespace only-white-space" { split_whitespace $' \t\n '; expect; }
@test "regex comma-or-semicolon" { split_regex 'a, b;c ,d' '[ ]*[,;][ ]*'; expect a b c d; }
@test "regex digit-runs" { split_regex 'a1b22c333' '[0-9]+'; expect a b c ''; }
@test "regex adjacent-matches" { split_regex 'a,;b' '[,;]'; expect a '' b; }
@test "regex leading-and-trailing" { split_regex ';a;' ';'; expect '' a ''; }
@test "regex empty" { split_regex '' '[,;]'; expect ''; }
@test "regex no-match" { split_regex 'abc' '[0-9]+'; expect abc; }
References
- The Python Standard Library, Built-in Types, str.split, str.split(sep=None, maxsplit=-1); str.isspace
- The Python Standard Library, re, Regular expression operations, re.split
- MDN Web Docs, String.prototype.split(), Parameters (separator, limit); Description
- Java SE 25 API, java.lang.String, split(String, int), split(String)
- Java SE 25 API, java.util.regex.Pattern, Predefined character classes (\s); UNICODE_CHARACTER_CLASS; quote(String); split(CharSequence, int)
- .NET API reference, String.Split, Split(Char[], Int32, StringSplitOptions), Remarks; Split(String, Int32, StringSplitOptions), Remarks
- .NET API reference, Regex.Split, Split(String, String), Remarks
- Go standard library, package strings, Split, SplitN, Fields
- Go standard library, package regexp, package overview; Regexp.Split
- The Rust Standard Library, primitive type str, split, splitn, split_whitespace, split_ascii_whitespace
- The regex crate for Rust, crate documentation
- F. Yergeau, RFC 3629, UTF-8, a transformation format of ISO 10646 (2003), Section 3, UTF-8 definition
- Go standard library, package unicode, IsSpace
- MDN Web Docs, Lexical grammar, White space
- cppreference.com, strtok, strtok_s
- The Open Group, POSIX.1-2024, regcomp, regerror, regexec, regfree, Description (REG_EXTENDED, REG_NOTBOL, pmatch[0])
- cppreference.com, std::ranges::split_view, std::views::split, Notes
- GNU Bash Reference Manual, Word Splitting
- GNU Bash Reference Manual, Shell Parameter Expansion, ${parameter#word}, ${parameter%%word}
- GNU Bash Reference Manual, Pattern Matching
- GNU Bash Reference Manual, Bash Builtin Commands, read, the -a and -d options
- GNU Bash Reference Manual, Conditional Constructs, [[ expression ]], the =~ operator and BASH_REMATCH
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 |
|
The native tests pass in 9 of 10 languages in this build.
Tag W33A9B Edit this page History Report an error Markdown