str_word_count
str_word_count(string $string, int $format = 0, ?string $characters = null): array|int
统计字符串中的单词:单词=字母数字串,可含(但不可起头于)' 与 -;format 0 返回数量、1 返回单词数组、2 返回「偏移→单词」映射——与 count_chars 的字符频次形成「字级 vs 字节级」对照;单字节实现,多字节文本需正则路线。
C C23
#include <ctype.h>
#include <stdio.h>
/* libc 无单词计数器:按 PHP 词规则单趟扫描——字母数字串,
词内允许 ' 与 - */
static int count_words(const char *s) {
int n = 0, in_word = 0;
for (; *s != '\0'; s++) {
int is_word_char = isalnum((unsigned char)*s) || *s == '\'' || *s == '-';
if (is_word_char && !in_word) {
n++;
in_word = 1;
} else if (!is_word_char) {
in_word = 0;
}
}
return n;
}
int main(void) {
printf("%d\n", count_words("the quick brown fox jumps")); /* 5 */
printf("%d\n", count_words("hello,world")); /* 2:逗号切分 */
printf("%d\n", count_words("don't stop-me")); /* 2:' 与 - 留在词内 */
return 0;
}
5 2 2
C++ C++26
#include <cctype>
#include <iostream>
#include <string>
// 标准库无单词计数器:按 PHP 词规则手写扫描器
static int count_words(const std::string &s) {
int n = 0;
bool in_word = false;
for (char ch : s) {
bool wc = std::isalnum(static_cast<unsigned char>(ch)) || ch == '\'' || ch == '-';
if (wc && !in_word) {
n++;
in_word = true;
} else if (!wc) {
in_word = false;
}
}
return n;
}
int main() {
std::cout << count_words("the quick brown fox jumps") << "\n"; // 5
std::cout << count_words("hello,world") << "\n"; // 2:逗号切分
std::cout << count_words("don't stop-me") << "\n"; // 2:' 与 - 留在词内
return 0;
}
5 2 2
C# v11.0.100
using System;
using System.Text.RegularExpressions;
// .NET 同样没有 str_word_count:按 PHP 词规则用 Regex.Matches;
// 空白切分路线(Split)是 Python split 的表亲
Console.WriteLine("the quick brown fox jumps".Split(' ', StringSplitOptions.RemoveEmptyEntries).Length); // 5
var word = new Regex(@"[A-Za-z]+(?:['-][A-Za-z]+)*");
Console.WriteLine(word.Matches("hello,world").Count); // 2——PHP 词规则
Console.WriteLine(word.Matches("don't stop-me").Count); // 2
5 2 2
Go v1.27.4
package main
import (
"fmt"
"regexp"
"strings"
)
// strings.Fields = 空白切分器(Python split 的表亲);
// PHP 词规则由手写正则复刻
func main() {
fmt.Println(len(strings.Fields("the quick brown fox jumps"))) // 5
fmt.Println(len(strings.Fields("hello,world"))) // 1——只认空白
word := regexp.MustCompile(`[A-Za-z]+(?:['-][A-Za-z]+)*`)
fmt.Println(len(word.FindAllString("hello,world", -1))) // 2——PHP 词规则
fmt.Println(len(word.FindAllString("don't stop-me", -1))) // 2
}
5 1 2 2
Java v27.0.1
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String s = "the quick brown fox jumps";
System.out.println(s.split("\\s+").length); // 5——空白切分路线
// PHP 词规则手写:字母数字串,词内可含 ' 或 -
Pattern word = Pattern.compile("[A-Za-z]+(?:['-][A-Za-z]+)*");
System.out.println(word.matcher("hello,world").results().count()); // 2
System.out.println(word.matcher("don't stop-me").results().count()); // 2
}
}
5 2 2
JavaScript v26.13.1
// 标准库无单词计数器——用一条正则手写 PHP 词规则;
// 规则要点:字母数字串可含词内 ' 或 -(但不能起头)
const words = (s) => s.match(/[A-Za-z]+(?:['-][A-Za-z]+)*/g) ?? [];
console.log(words("the quick brown fox jumps").length); // 5
console.log(words("hello,world").length); // 2——PHP 词规则,不是 split()
console.log(words("don't stop-me").length); // 2
5 2 2
PHP v8.6.0
// str_word_count():单词=字母数字串,可含(但不可起头于)' 与 -;
// 依赖 locale、单字节实现——字节级对照是 count_chars(A41)
$s = "the quick brown fox jumps";
echo str_word_count($s), "\n"; // 5——纯空白文本:与 len(split()) 一致
echo str_word_count("hello,world"), "\n"; // 2:逗号不是词字符,PHP 看到两个词
echo str_word_count("don't stop-me"), "\n"; // 2:' 与 - 留在词内
print_r(str_word_count($s, 1)); // format 1:单词数组
echo preg_match_all('/\p{L}+/u', "caf\u{e9} au lait"), "\n"; // 3——多字节需正则路线
5
2
2
Array
(
[0] => the
[1] => quick
[2] => brown
[3] => fox
[4] => jumps
)
3
Python v3.15.2
import re
# len(split()):Python 的词计数以空白为准——标点规则与 PHP 不同;
# 需要时用正则对齐
s = "the quick brown fox jumps"
print(len(s.split())) # 5
print(len("hello,world".split())) # 1——Python 把 "hello,world" 当作一个 token
print(len("don't stop-me".split())) # 2
print(len(re.findall(r"[^\W\d_]+", "caf\u00e9 au lait"))) # 3——只算 Unicode 字母
5 1 2 3
Rust v1.99.1
// 标准库无单词计数器:split_whitespace 是 Python split 的表亲;
// PHP 词规则一步之遥——字母数字 + 词内 ' 或 -
fn count_words(s: &str) -> usize {
s.split(|c: char| !(c.is_alphanumeric() || c == '\'' || c == '-'))
.filter(|w| !w.is_empty())
.count()
}
fn main() {
println!("{}", "the quick brown fox jumps".split_whitespace().count()); // 5
println!("{}", count_words("hello,world")); // 2——PHP 词规则
println!("{}", count_words("don't stop-me")); // 2
}
5 2 2
TypeScript v26.13.1
// 标准库无单词计数器——用一条正则手写 PHP 词规则;
// 规则要点:字母数字串可含词内 ' 或 -(但不能起头)
const words = (s: string): string[] => s.match(/[A-Za-z]+(?:['-][A-Za-z]+)*/g) ?? [];
console.log(words("the quick brown fox jumps").length); // 5
console.log(words("hello,world").length); // 2——PHP 词规则,不是 split()
console.log(words("don't stop-me").length); // 2
5 2 2
语言差异说明
字级 vs 字节级:count_chars(A41)回答「每个字节出现几次」,本条回答「有几个词」——两个粒度互补;本条确定性断言:固定句 "the quick brown fox jumps" 恒 5 词、"hello,world" 恒 2(逗号切词)、"don't stop-me" 恒 2(' 与 - 留在词内)——全部与 locale 无关的固定输入。
PHP:str_word_count($s, $format, $characters) 的 format 0=数量/1=单词数组/2=偏移→单词映射;$characters 可追加词字符(如数字);注意:单词定义依赖 locale(setlocale 可改变 a-z 之外的范围)且不支持多字节——中文/带重音文本请走 preg_split('/\p{L}+/u', ...);format 非 0/1/2 抛 ValueError(PHP 8.0 起)。
Python:len(s.split()) 是空白切分口径——"hello,world" 算 1 个 token(PHP 算 2),两个口径的差就是「标点是否切词」;Unicode 词规则用 re.findall(r"[^\W\d_]+", ...)(\w 减去数字下划线)。
Go:strings.Fields 同 Python split 口径;PHP 词规则用 regexp.MustCompile("[A-Za-z]+(?:['-][A-Za-z]+)*") 复刻。
Java:split("\\s+") 空白口径;PHP 词规则用 Pattern + Matcher.results().count()(Java 9+ 流式计数)。
C#:Regex.Matches(...).Count 是最短的词规则复刻;Split(' ', RemoveEmptyEntries) 是空白口径。
JavaScript/TypeScript:String.match 全局正则即手写版;?? [] 兜住无匹配返回 null 的坑。
C/C++:libc/libstdc++ 无词计数器——单趟状态机(in_word 翻转)就是 str_word_count 的实现原理;isalnum 受 locale 影响(C locale 下即 a-zA-Z0-9)。
Rust:split_whitespace 空白口径;split(谓词) + filter(非空) 一步复刻 PHP 词规则,char::is_alphanumeric 天然 Unicode。