空字符串是长度为零的唯一字符串。
空字符串是连接操作的标识元素。
按照字典顺序,空字符串在任何其他字符串之前,因为它是所有字符串中最短的。
空字符串是合法的字符串,大多数字符串操作都应该在该字符串上工作。
Wikipedia
> strlen("");
=> 0
> "a" . "" == "a";
=> true
> "" . "a" == "a";
=> true
> "" < "\0";
=> true
从上面看来,PHP 似乎将空字符串视为有效字符串。
> strstr("lolsome", "");
strstr(): Empty needle :1
但它似乎并不认为空字符串是完全合法的。很可能 PHP 是唯一一种不允许在字符串中搜索子字符串为空字符串的语言。
这是一种防御机制吗?显然,程序员不必用if 来保护针。如果是这样,为什么其他语言允许这个测试通过!!!语言设计师必须回答
Python 字符串是由什么组成的?
>>> ''.count('')
1
显然空字符串有一个空字符串。
>>> 'a'.count('')
2
一个元素字符串有两个空字符串。
>>> 'ab'.count('')
3
所以看起来 Python 字符串是一个元素字符串的串联。字符串中的每个元素都夹在两个空字符串之间。
>>> "lolsome".split('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: empty separator
但这里 Python 与空字符串的有效性相矛盾。 这是一个错误吗?
Ruby 和 JavaScript 在此处通过测试。
> "lolsome".split("")
=> ["l", "o", "l", "s", "o", "m", "e"]
我从Rosetta code 编译了几个语言示例,有趣注意到它们都在子字符串搜索中允许空字符串并返回 true。
AWK
awk 'BEGIN { print index("lolsome", "") != 0 }'
C
int main() {
printf("%d\n", strstr("lolsome", "") != NULL);
return 0;
}
C++
#include <iostream>
#include <string>
int main() {
std::string s = "lolsome";
std::cout << (s.find("") != -1) << "\n";
return 0;
}
C#
using System;
class MainClass {
public static void Main (string[] args) {
string s = "lolsome";
Console.WriteLine(s.IndexOf("", 0, s.Length) != -1);
}
}
Clojure
(println (.indexOf "lolsome" ""))
Go
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Index("lolsome", "") != -1)
}
时髦
println 'lolsome'.indexOf('')
返回 0,错误返回 -1
Java
class Main {
public static void main(String[] args) {
System.out.println("lolsome".indexOf("") != -1);
}
}
JavaScript
"lolsome".indexOf("") != -1
Lua
s = "lolsome"
print(s:find "" ~= nil)
Perl
print index("lolsome", "") != -1;
Python
"lolsome".find("") != -1
Ruby
"lolsome".index("") != nil