Taskintro
Check whether a string is empty
Also called empty string, is empty, isEmpty, blank string, isBlank, IsNullOrEmpty, IsNullOrWhiteSpace, string has only white space.
Check whether a string has no characters, check whether it has only white space, and know which values each language also treats as empty and which characters it calls white space.
- Evidence
- Code in 10 languages
Task
Check whether a string is empty. The function is_empty(s) returns true if s has no code points. The function is_blank(s) returns true if each code point of s is ASCII white space: space, tab, line feed, vertical tab, form feed or carriage return. Both functions return true for the empty string. For example, is_empty(" ") is false, and is_blank(" ") is true.
A string of invisible characters, such as U+200B ZERO WIDTH SPACE, is not empty, and it is not blank. The languages do not agree on which code points are white space, so the contract uses only the six ASCII code points.
Solutions
| Language | Empty | Blank in the contract | Blank in the library |
|---|---|---|---|
| Python | len(s) == 0 |
s.strip(" \t\n\v\f\r") == "" |
not s or s.isspace() |
| JavaScript, TypeScript | s.length === 0 |
/^[ \t\n\v\f\r]*$/.test(s) |
s.trim() === "" |
| Java | s.isEmpty() |
allMatch on s.chars() |
s.isBlank() |
| C# | s.Length == 0 |
s.AsSpan().Trim(...).IsEmpty |
string.IsNullOrWhiteSpace(s) |
| Go | s == "" |
strings.Trim(s, ...) == "" |
strings.TrimSpace(s) == "" |
| Rust | s.is_empty() |
all on s.chars() |
s.trim().is_empty() |
| C | s[0] == '\0' |
s[strspn(s, ...)] == '\0' |
a loop with isspace |
| C++ | s.empty() |
s.find_first_not_of(...) == npos |
none |
| Bash | [[ -z $s ]] |
[[ -z ${s//[$' \t\n\v\f\r']/} ]] |
[[ $s != *[![:space:]]* ]] |
- Python. The length of an empty string is 0. In a condition, "empty sequences and collections"1 are false, so
not sis also a test.str.isspacereturns true "if there are only whitespace characters in the string and there is at least one character"1. - JavaScript and TypeScript.
lengthcounts UTF-16 code units, and it is 0 only for the empty string. The code tests the blank string with a character class, becausetrimremoves more than the ASCII white space. - Java.
isEmpty"Returns true if, and only if, length() is 0"2.isBlank"Returns true if the string is empty or contains only white space codepoints"2, with the Java rules for white space. - C#.
Lengthis 0 only for the empty string.IsNullOrWhiteSpace"Indicates whether a specified string is null, empty, or consists only of white-space characters"3. - Go. A Go string cannot be
nil, and the zero value of a string is"". Sos == ""andlen(s) == 0are the same test. - Rust.
is_empty"Returns true if self has a length of zero bytes"4. The code lists the six characters foris_blank. - C. A C string ends at its first null character, so the string is empty when its first byte is
'\0'.strspngives the length of the first part ofsthat has only white space, and the string is blank when that part ends at the null character. - C++.
empty"Checks if the string has no characters"5.find_first_not_ofreturnsnposwhen no character is outside the set. - Bash. In a conditional expression,
-z stringis "True if the length of string is zero"6. The expansion deletes each ASCII white space character, and the test checks that nothing is left.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of is_blank are in cases/blank.jsonl.
emptyandblank-empty: the empty string is empty, and it is also blank.space,newlineandnbsp: white space is not empty.blank-mixedandblank-vt-ff: each of the six ASCII white space characters is blank, also the vertical tab U+000B and the form feed U+000C.blank-nbspandblank-ideographic: U+00A0 NO-BREAK SPACE and U+3000 IDEOGRAPHIC SPACE are not ASCII, so they are not blank in the contract. Most library functions call them white space.zero-widthandblank-zero-width: U+200B is not empty, and it is not white space in any of the libraries.combining,astralandcjk: a single combining mark, an emoji or a CJK character is not empty.
Pitfalls
- Python not s is also true for None.
not sis true forNone, for0and for each empty collection, not only for the empty string.''.isspace()is false, so a blank test withisspacemust also check for the empty string.isspaceaccepts U+00A0, but not U+200B:
for s in ["", None, " "]:
print(repr(s), not s)
print("".isspace(), "\u00a0".isspace(), "\u200b".isspace())
'' True
None True
' ' False
False True False
- JavaScript !s is true for more than the empty string. A falsy value "is considered false when encountered in a Boolean context"7, and the falsy values include
0,nullandundefined.trimremoves Unicode spaces, because "Whitespace is defined as white space characters plus line terminators"8, but it does not remove U+200B:
for (const v of ["", 0, null, " "]) {
console.log(JSON.stringify(v), !v);
}
console.log("\u00a0\u3000".trim() === "");
console.log("\u200b".trim().length);
"" true
0 true
null true
" " false
true
1
- Java isBlank does not accept the no-break space. A Java white space character is "a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space"9. So U+2003 EM SPACE is blank, and U+00A0 is not. A call on
nullthrows aNullPointerException:
public class Main {
public static void main(String[] args) {
System.out.println("\u2003".isBlank());
System.out.println("\u00a0".isBlank());
String s = null;
try {
System.out.println(s.isEmpty());
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
}
}
true
false
NullPointerException
- C# IsNullOrWhiteSpace uses Unicode. "White-space characters are defined by the Unicode standard"3, so U+00A0 and U+3000 are white space, and U+200B is not.
s.Lengthon anullstring throws, so test fornullfirst, or uses?.Length == 0, which is false fornull:
using System;
string? s = null;
Console.WriteLine(string.IsNullOrEmpty(s));
Console.WriteLine(string.IsNullOrWhiteSpace("\u00a0\u3000"));
Console.WriteLine(string.IsNullOrWhiteSpace("\u200b"));
Console.WriteLine(s?.Length == 0);
True
True
False
False
- Go TrimSpace uses Unicode.
TrimSpaceremoves white space "as defined by Unicode"10.unicode.IsSpacefollows "Unicode's White Space property"11, so U+00A0 and U+3000 are white space, and U+200B is not:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
var s string
fmt.Println(s == "", len(s))
fmt.Println(strings.TrimSpace("\u00a0\u3000") == "")
fmt.Println(unicode.IsSpace('\u200b'))
}
true 0
true
false
- Rust is_ascii_whitespace does not accept the vertical tab. "Because the list above excludes U+000B VERTICAL TAB, c.is_ascii_whitespace() is not equivalent to c.is_ascii() && c.is_whitespace()"12. A value that can be missing is an
Option, so test it withis_none_or:
fn main() {
println!("{}", "\u{a0}\u{3000}".trim().is_empty());
println!("{}", '\x0B'.is_ascii_whitespace());
println!("{}", '\x0B'.is_whitespace());
let name: Option<&str> = None;
println!("{}", name.is_none_or(str::is_empty));
}
true
false
true
true
- C isspace needs an unsigned char. "The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF"13. A byte such as 0xC2 is negative in a signed
char, so cast it first. ANULLpointer is not an empty string, and the code must test the pointer before it reads the first byte:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
// The cast to unsigned char keeps a byte such as 0xC2 from being negative.
static bool is_blank_locale(const char *s) {
for (; *s != '\0'; s++) {
if (!isspace((unsigned char)*s)) {
return false;
}
}
return true;
}
int main(void) {
const char *p = NULL;
// Test the pointer before the first byte.
printf("%d\n", p == NULL || p[0] == '\0');
printf("%d %d\n", is_blank_locale(" \t"), is_blank_locale("\xc2\xa0"));
return 0;
}
1
1 0
- C++ empty does not clear the string.
empty()only returns a result.clear()removes the characters:
#include <iostream>
#include <string>
int main() {
std::string s = "text";
// empty() only reads the string. clear() is the call that removes the text.
std::cout << s.empty() << " " << s.size() << "\n";
s.clear();
std::cout << s.empty() << " " << s.size() << "\n";
}
0 4
1 0
- Bash test with an unquoted variable. In
[ -n $s ], an emptysdisappears, and[sees one argument. With one argument, "The expression is true if, and only if, the argument is not null"6, so the test is true for the empty string. A value with a space gives two arguments, and[reports an error. Quote the variable, or use[[:
s=''
[ -n $s ] && echo "unquoted -n: true"
[ -n "$s" ] || echo "quoted -n: false"
s='a b'
[ -z "$s" ] || echo "quoted -z: false"
[ -z $s ] 2>/dev/null || echo "unquoted -z: error or false"
unquoted -n: true
quoted -n: false
quoted -z: false
unquoted -z: error or false
Related tasks
- Trim white space: remove the white space at the ends of a string.
- Find the length of a string: count the code units, code points or bytes of a string.
- Compare strings: compare a string with the empty string or with another string.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
# The six code points of ASCII white space.
ASCII_SPACE = " \t\n\v\f\r"
def is_empty(s: str) -> bool:
"""Return True if s has no code points."""
return len(s) == 0
def is_blank(s: str) -> bool:
"""Return True if each code point of s is ASCII white space."""
# str.isspace is False for the empty string, and it also accepts
# Unicode spaces, so the code strips the six code points instead.
return s.strip(ASCII_SPACE) == ""
test_empty.py 44 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
import pytest
from empty import is_blank, is_empty
# U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
EMPTY = {
"letter": ("a", False),
"word": ("hello", False),
"empty": ("", True),
"space": (" ", False),
"newline": ("\n", False),
"nbsp": ("\u00a0", False),
"zero-width": ("\u200b", False),
"combining": ("\u0301", False),
"astral": ("\U0001f642", False),
"cjk": ("日", False),
}
BLANK = {
"blank-empty": ("", True),
"blank-space": (" ", True),
"blank-mixed": (" \t\n\r", True),
"blank-vt-ff": ("\v\f", True),
"blank-letter": ("a", False),
"blank-padded": (" a ", False),
"blank-nbsp": ("\u00a0", False),
"blank-zero-width": ("\u200b", False),
"blank-ideographic": ("\u3000", False),
"blank-astral": (" \U0001f642 ", False),
}
@pytest.mark.parametrize("name", EMPTY)
def test_is_empty(name):
s, want = EMPTY[name]
assert is_empty(s) is want
@pytest.mark.parametrize("name", BLANK)
def test_is_blank(name):
s, want = BLANK[name]
assert is_blank(s) is want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
#include "empty.hpp"
bool is_empty(std::string_view s) {
return s.empty();
}
bool is_blank(std::string_view s) {
return s.find_first_not_of(" \t\n\v\f\r") == std::string_view::npos;
}
empty.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
#ifndef EMPTY_HPP
#define EMPTY_HPP
#include <string_view>
// is_empty reports whether s has no characters.
bool is_empty(std::string_view s);
// is_blank reports whether each byte of s is ASCII white space.
bool is_blank(std::string_view s);
#endif
test_empty.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
#include "empty.hpp"
#include <string_view>
#include <iostream>
static int failures = 0;
static void check(std::string_view name, bool got, bool want) {
if (got != want) {
std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
failures++;
}
}
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
int main() {
check("letter", is_empty("a"), false);
check("word", is_empty("hello"), false);
check("empty", is_empty(""), true);
check("space", is_empty(" "), false);
check("newline", is_empty("\n"), false);
check("nbsp", is_empty("\xc2\xa0"), false);
check("zero-width", is_empty("\xe2\x80\x8b"), false);
check("combining", is_empty("\xcc\x81"), false);
check("astral", is_empty("\xf0\x9f\x99\x82"), false);
check("cjk", is_empty("日"), false);
check("blank-empty", is_blank(""), true);
check("blank-space", is_blank(" "), true);
check("blank-mixed", is_blank(" \t\n\r"), true);
check("blank-vt-ff", is_blank("\v\f"), true);
check("blank-letter", is_blank("a"), false);
check("blank-padded", is_blank(" a "), false);
check("blank-nbsp", is_blank("\xc2\xa0"), false);
check("blank-zero-width", is_blank("\xe2\x80\x8b"), false);
check("blank-ideographic", is_blank("\xe3\x80\x80"), false);
check("blank-astral", is_blank(" \xf0\x9f\x99\x82 "), false);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
/** Checks whether a string is empty or has only ASCII white space. */
public final class Empty {
private Empty() {}
/** Returns true if s has no characters. */
public static boolean isEmpty(String s) {
return s.isEmpty();
}
/** Returns true if each character of s is ASCII white space. */
public static boolean isBlank(String s) {
// isBlank() uses Character.isWhitespace, which also accepts Unicode spaces.
return s.chars().allMatch(c -> " \t\n\u000b\f\r".indexOf(c) >= 0);
}
}
EmptyTest.java 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
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 EmptyTest {
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
static Stream<Arguments> empty() {
return Stream.of(
Arguments.of("letter", "a", false),
Arguments.of("word", "hello", false),
Arguments.of("empty", "", true),
Arguments.of("space", " ", false),
Arguments.of("newline", "\n", false),
Arguments.of("nbsp", "\u00a0", false),
Arguments.of("zero-width", "\u200b", false),
Arguments.of("combining", "\u0301", false),
Arguments.of("astral", "\ud83d\ude42", false),
Arguments.of("cjk", "日", false));
}
static Stream<Arguments> blank() {
return Stream.of(
Arguments.of("blank-empty", "", true),
Arguments.of("blank-space", " ", true),
Arguments.of("blank-mixed", " \t\n\r", true),
Arguments.of("blank-vt-ff", "\u000b\f", true),
Arguments.of("blank-letter", "a", false),
Arguments.of("blank-padded", " a ", false),
Arguments.of("blank-nbsp", "\u00a0", false),
Arguments.of("blank-zero-width", "\u200b", false),
Arguments.of("blank-ideographic", "\u3000", false),
Arguments.of("blank-astral", " \ud83d\ude42 ", false));
}
@ParameterizedTest(name = "{0}")
@MethodSource("empty")
void isEmpty(String name, String s, boolean want) {
assertEquals(want, Empty.isEmpty(s));
}
@ParameterizedTest(name = "{0}")
@MethodSource("blank")
void isBlank(String name, String s, boolean want) {
assertEquals(want, Empty.isBlank(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
#include "empty.h"
#include <string.h>
bool is_empty(const char *s) {
// The first byte is the null character only in the empty string.
return s[0] == '\0';
}
bool is_blank(const char *s) {
// strspn gives the length of the first part of s that has only these bytes.
return s[strspn(s, " \t\n\v\f\r")] == '\0';
}
empty.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
#ifndef EMPTY_H
#define EMPTY_H
#include <stdbool.h>
// is_empty reports whether the string s has no characters. s must not be NULL.
bool is_empty(const char *s);
// is_blank reports whether each byte of s is ASCII white space.
bool is_blank(const char *s);
#endif
test_empty.c 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
#include "empty.h"
#include <stdbool.h>
#include <stdio.h>
static int failures = 0;
static void check(const char *name, bool got, bool want) {
if (got != want) {
fprintf(stderr, "case %s: got %d, want %d\n", name, got, want);
failures++;
}
}
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
int main(void) {
check("letter", is_empty("a"), false);
check("word", is_empty("hello"), false);
check("empty", is_empty(""), true);
check("space", is_empty(" "), false);
check("newline", is_empty("\n"), false);
check("nbsp", is_empty("\xc2\xa0"), false);
check("zero-width", is_empty("\xe2\x80\x8b"), false);
check("combining", is_empty("\xcc\x81"), false);
check("astral", is_empty("\xf0\x9f\x99\x82"), false);
check("cjk", is_empty("日"), false);
check("blank-empty", is_blank(""), true);
check("blank-space", is_blank(" "), true);
check("blank-mixed", is_blank(" \t\n\r"), true);
check("blank-vt-ff", is_blank("\v\f"), true);
check("blank-letter", is_blank("a"), false);
check("blank-padded", is_blank(" a "), false);
check("blank-nbsp", is_blank("\xc2\xa0"), false);
check("blank-zero-width", is_blank("\xe2\x80\x8b"), false);
check("blank-ideographic", is_blank("\xe3\x80\x80"), false);
check("blank-astral", is_blank(" \xf0\x9f\x99\x82 "), false);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
using System;
/// <summary>Checks whether a string is empty or has only ASCII white space.</summary>
public static class Empty
{
public static bool IsEmpty(string s) => s.Length == 0;
// string.IsNullOrWhiteSpace uses char.IsWhiteSpace, which also accepts
// Unicode spaces, so the code trims the six ASCII characters instead.
public static bool IsBlank(string s) => s.AsSpan().Trim(" \t\n\v\f\r").IsEmpty;
}
EmptyTests.cs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
using Xunit;
public sealed class EmptyTests
{
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
public static TheoryData<string, string, bool> EmptyCases => new()
{
{ "letter", "a", false },
{ "word", "hello", false },
{ "empty", "", true },
{ "space", " ", false },
{ "newline", "\n", false },
{ "nbsp", "\u00a0", false },
{ "zero-width", "\u200b", false },
{ "combining", "\u0301", false },
{ "astral", "\U0001f642", false },
{ "cjk", "日", false },
};
public static TheoryData<string, string, bool> BlankCases => new()
{
{ "blank-empty", "", true },
{ "blank-space", " ", true },
{ "blank-mixed", " \t\n\r", true },
{ "blank-vt-ff", "\v\f", true },
{ "blank-letter", "a", false },
{ "blank-padded", " a ", false },
{ "blank-nbsp", "\u00a0", false },
{ "blank-zero-width", "\u200b", false },
{ "blank-ideographic", "\u3000", false },
{ "blank-astral", " \U0001f642 ", false },
};
[Theory]
[MemberData(nameof(EmptyCases))]
public void IsEmpty(string name, string s, bool want)
{
Assert.NotNull(name);
Assert.Equal(want, Empty.IsEmpty(s));
}
[Theory]
[MemberData(nameof(BlankCases))]
public void IsBlank(string name, string s, bool want)
{
Assert.NotNull(name);
Assert.Equal(want, Empty.IsBlank(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
// isEmpty reports whether s has no code points.
export function isEmpty(s) {
return s.length === 0;
}
// isBlank reports whether each code point of s is ASCII white space. trim()
// also removes Unicode spaces, so the code uses a character class instead.
export function isBlank(s) {
return /^[ \t\n\v\f\r]*$/.test(s);
}
empty.test.js 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isBlank, isEmpty } from "./empty.js";
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
const empty = [
["letter", "a", false],
["word", "hello", false],
["empty", "", true],
["space", " ", false],
["newline", "\n", false],
["nbsp", "\u00a0", false],
["zero-width", "\u200b", false],
["combining", "\u0301", false],
["astral", "\u{1f642}", false],
["cjk", "日", false],
];
const blank = [
["blank-empty", "", true],
["blank-space", " ", true],
["blank-mixed", " \t\n\r", true],
["blank-vt-ff", "\v\f", true],
["blank-letter", "a", false],
["blank-padded", " a ", false],
["blank-nbsp", "\u00a0", false],
["blank-zero-width", "\u200b", false],
["blank-ideographic", "\u3000", false],
["blank-astral", " \u{1f642} ", false],
];
for (const [name, s, want] of empty) {
test(name, () => {
assert.equal(isEmpty(s), want);
});
}
for (const [name, s, want] of blank) {
test(name, () => {
assert.equal(isBlank(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
// isEmpty reports whether s has no code points.
export function isEmpty(s: string): boolean {
return s.length === 0;
}
// isBlank reports whether each code point of s is ASCII white space. trim()
// also removes Unicode spaces, so the code uses a character class instead.
export function isBlank(s: string): boolean {
return /^[ \t\n\v\f\r]*$/.test(s);
}
empty.test.ts 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isBlank, isEmpty } from "./empty.ts";
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
const empty = [
["letter", "a", false],
["word", "hello", false],
["empty", "", true],
["space", " ", false],
["newline", "\n", false],
["nbsp", "\u00a0", false],
["zero-width", "\u200b", false],
["combining", "\u0301", false],
["astral", "\u{1f642}", false],
["cjk", "日", false],
];
const blank = [
["blank-empty", "", true],
["blank-space", " ", true],
["blank-mixed", " \t\n\r", true],
["blank-vt-ff", "\v\f", true],
["blank-letter", "a", false],
["blank-padded", " a ", false],
["blank-nbsp", "\u00a0", false],
["blank-zero-width", "\u200b", false],
["blank-ideographic", "\u3000", false],
["blank-astral", " \u{1f642} ", false],
];
for (const [name, s, want] of empty) {
test(name, () => {
assert.equal(isEmpty(s), want);
});
}
for (const [name, s, want] of blank) {
test(name, () => {
assert.equal(isBlank(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
// Package empty checks whether a string is empty or has only ASCII white space.
package empty
import "strings"
// IsEmpty reports whether s has no bytes.
func IsEmpty(s string) bool {
return s == ""
}
// IsBlank reports whether each byte of s is ASCII white space. strings.TrimSpace
// also removes Unicode spaces, so the code gives the six bytes to Trim.
func IsBlank(s string) bool {
return strings.Trim(s, " \t\n\v\f\r") == ""
}
empty_test.go 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
package empty
import "testing"
type emptyCase struct {
name, s string
want bool
}
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
var emptyCases = []emptyCase{
{"letter", "a", false},
{"word", "hello", false},
{"empty", "", true},
{"space", " ", false},
{"newline", "\n", false},
{"nbsp", "\u00a0", false},
{"zero-width", "\u200b", false},
{"combining", "\u0301", false},
{"astral", "\U0001f642", false},
{"cjk", "日", false},
}
var blankCases = []emptyCase{
{"blank-empty", "", true},
{"blank-space", " ", true},
{"blank-mixed", " \t\n\r", true},
{"blank-vt-ff", "\v\f", true},
{"blank-letter", "a", false},
{"blank-padded", " a ", false},
{"blank-nbsp", "\u00a0", false},
{"blank-zero-width", "\u200b", false},
{"blank-ideographic", "\u3000", false},
{"blank-astral", " \U0001f642 ", false},
}
func TestIsEmpty(t *testing.T) {
for _, c := range emptyCases {
if got := IsEmpty(c.s); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestIsBlank(t *testing.T) {
for _, c := range blankCases {
if got := IsBlank(c.s); 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/check-whether-a-string-is-empty/.
/// Returns true if s has no bytes.
pub fn is_empty(s: &str) -> bool {
s.is_empty()
}
/// Returns true if each character of s is ASCII white space. The code lists
/// the six characters, because char::is_ascii_whitespace does not accept
/// U+000B and str::trim also removes Unicode spaces.
pub fn is_blank(s: &str) -> bool {
s.chars()
.all(|c| matches!(c, ' ' | '\t' | '\n' | '\x0B' | '\x0C' | '\r'))
}
tests/empty_test.rs 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
use algo_check_whether_a_string_is_empty::{is_blank, is_empty};
// U+00A0 is NO-BREAK SPACE, U+200B is ZERO WIDTH SPACE, and U+3000 is IDEOGRAPHIC SPACE. None of them is ASCII white space.
#[test]
fn empty() {
let cases = [
("letter", "a", false),
("word", "hello", false),
("empty", "", true),
("space", " ", false),
("newline", "\n", false),
("nbsp", "\u{a0}", false),
("zero-width", "\u{200b}", false),
("combining", "\u{301}", false),
("astral", "\u{1f642}", false),
("cjk", "日", false),
];
for (name, s, want) in cases {
assert_eq!(is_empty(s), want, "{name}");
}
}
#[test]
fn blank() {
let cases = [
("blank-empty", "", true),
("blank-space", " ", true),
("blank-mixed", " \t\n\r", true),
("blank-vt-ff", "\x0b\x0c", true),
("blank-letter", "a", false),
("blank-padded", " a ", false),
("blank-nbsp", "\u{a0}", false),
("blank-zero-width", "\u{200b}", false),
("blank-ideographic", "\u{3000}", false),
("blank-astral", " \u{1f642} ", false),
];
for (name, s, want) in cases {
assert_eq!(is_blank(s), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
# is_empty S: exits with status 0 if S is the empty string. The [[ keyword does
# not split words, so the test is correct also when S has spaces.
is_empty() {
[[ -z $1 ]]
}
# is_blank S: exits with status 0 if each character of S is ASCII white space.
# The expansion deletes the six characters, and the test checks what is left.
is_blank() {
[[ -z ${1//[$' \t\n\v\f\r']/} ]]
}
test_empty.bats 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-empty/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/empty.sh"
}
check() { # check STATUS FUNCTION S
run "$2" "$3"
[ "$status" -eq "$1" ]
[ "$output" = "" ]
}
# C2 A0 is U+00A0 NO-BREAK SPACE, E2 80 8B is U+200B, and E3 80 80 is U+3000.
@test "letter" { check 1 is_empty 'a'; }
@test "word" { check 1 is_empty 'hello'; }
@test "empty" { check 0 is_empty ''; }
@test "space" { check 1 is_empty ' '; }
@test "newline" { check 1 is_empty $'\n'; }
@test "nbsp" { check 1 is_empty $'\xc2\xa0'; }
@test "zero-width" { check 1 is_empty $'\xe2\x80\x8b'; }
@test "combining" { check 1 is_empty $'\xcc\x81'; }
@test "astral" { check 1 is_empty $'\xf0\x9f\x99\x82'; }
@test "cjk" { check 1 is_empty '日'; }
@test "blank-empty" { check 0 is_blank ''; }
@test "blank-space" { check 0 is_blank ' '; }
@test "blank-mixed" { check 0 is_blank $' \t\n\r'; }
@test "blank-vt-ff" { check 0 is_blank $'\v\f'; }
@test "blank-letter" { check 1 is_blank 'a'; }
@test "blank-padded" { check 1 is_blank ' a '; }
@test "blank-nbsp" { check 1 is_blank $'\xc2\xa0'; }
@test "blank-zero-width" { check 1 is_blank $'\xe2\x80\x8b'; }
@test "blank-ideographic" { check 1 is_blank $'\xe3\x80\x80'; }
@test "blank-astral" { check 1 is_blank $' \xf0\x9f\x99\x82 '; }
References
- The Python Standard Library, Built-in Types, Truth Value Testing; str.isspace
- Java SE 25 API, java.lang.String, isEmpty(); isBlank()
- .NET API reference, String.IsNullOrWhiteSpace method, Remarks
- The Rust Standard Library, primitive type str, is_empty, trim
- cppreference.com, std::basic_string empty
- Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Bash Conditional Expressions; Bourne Shell Builtins, test
- MDN Web Docs Glossary, Falsy
- MDN Web Docs, String.prototype.trim(), Return value
- Java SE 25 API, java.lang.Character, isWhitespace(char)
- Go standard library, package strings, TrimSpace
- Go standard library, package unicode, IsSpace
- The Rust Standard Library, primitive type char, is_ascii_whitespace
- cppreference.com, isspace
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 0WBE1M Edit this page History Report an error Markdown