ucwords

ucwords(string $string, string $separators = " \t\r\n\f\v"): string

把每个词的首字母转为大写。默认词边界只有六种空白字符(空格/制表/回车/换行/换页/垂直制表),撇号和连字符都不算——与 Python title()、C# ToTitleCase 的规则各不相同,各家差异见对照表。

C C23

C23
#include <ctype.h>
#include <stdio.h>

int main(void) {
    const char *s = "hello world";
    int word_start = 1; // 串首字符即开启一个词
    for (const char *p = s; *p != '\0'; ++p) {
        if (*p == ' ') { // 分隔符:下一字符开启新词
            word_start = 1;
            putchar(*p);
        } else {
            putchar(word_start ? toupper((unsigned char)*p) : *p);
            word_start = 0;
        }
    }
    putchar('\n');
    return 0;
}
输出
Hello World

C++ C++26

C++26
#include <cctype>
#include <iostream>

int main() {
    const char *s = "hello world";
    bool word_start = true; // 串首即开启一个词
    for (const char *p = s; *p != '\0'; ++p) {
        if (*p == ' ') { // 分隔符:下一字符开启新词
            word_start = true;
            std::cout << *p;
        } else {
            std::cout << (word_start ? (char)toupper((unsigned char)*p) : *p);
            word_start = false;
        }
    }
    std::cout << "\n";
    return 0;
}
输出
Hello World

C# v11.0.100

v11.0.100
// TextInfo.ToTitleCase 是最接近的内置(文化相关——此处钉死 InvariantCulture)
var ti = System.Globalization.CultureInfo.InvariantCulture.TextInfo;
Console.WriteLine(ti.ToTitleCase("hello world")); // Hello World
Console.WriteLine(ti.ToTitleCase("mike o'hara")); // Mike O'hara:撇号不是词边界
Console.WriteLine(ti.ToTitleCase("hello-world")); // Hello-World:连字符反而是词边界
输出
Hello World
Mike O'hara
Hello-World

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
	"unicode"
)

// 无内置:strings.Title 已于 Go 1.18 弃用——手写状态机
func ucwords(s string) string {
	word_start := true
	return strings.Map(func(r rune) rune {
		if unicode.IsSpace(r) {
			word_start = true
			return r
		}
		if word_start {
			word_start = false
			return unicode.ToUpper(r)
		}
		return r
	}, s)
}

func main() {
	fmt.Println(ucwords("hello world")) // Hello World
}
输出
Hello World

Java v27.0.1

v27.0.1
public class Main {
    // 无内置标题大小写——手写状态机
    //(Apache commons-lang 的 WordUtils 是经典第三方方案)
    static String ucwords(String s) {
        StringBuilder sb = new StringBuilder(s);
        boolean word_start = true;
        for (int i = 0; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (Character.isWhitespace(c)) {
                word_start = true;
            } else {
                if (word_start) sb.setCharAt(i, Character.toUpperCase(c));
                word_start = false;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(ucwords("hello world")); // Hello World
    }
}
输出
Hello World

JavaScript v26.13.1

v26.13.1
// 无内置标题大小写——手写状态机
function ucwords(s) {
  let out = ""
  let word_start = true
  for (const c of s) {
    if (c === " ") {
      word_start = true
      out += c
    } else {
      out += word_start ? c.toUpperCase() : c
      word_start = false
    }
  }
  return out
}
console.log(ucwords("hello world")) // Hello World
输出
Hello World

PHP v8.6.0

v8.6.0
echo ucwords("hello world"), "\n";      // Hello World
echo ucwords("mike o'hara"), "\n";      // Mike O'hara:撇号不是词边界
echo ucwords("hello-world"), "\n";      // Hello-world:连字符也不是
echo ucwords("hello-world", "-"), "\n"; // Hello-World:第二参数自定义分隔符
输出
Hello World
Mike O'hara
Hello-world
Hello-World

Python v3.15.2

v3.15.2
print("hello world".title())  # Hello World
# title() 把撇号和连字符都当词边界——与 PHP 的已知差异:
print("mike o'hara".title())   # Mike O'Hara
print("hello-world".title())   # Hello-World
输出
Hello World
Mike O'Hara
Hello-World

Rust v1.99.1

v1.99.1
// 无内置标题大小写——手写状态机
fn ucwords(s: &str) -> String {
    let mut word_start = true;
    s.chars()
        .map(|c| {
            if c.is_whitespace() {
                word_start = true;
                c
            } else if word_start {
                word_start = false;
                c.to_uppercase().next().unwrap()
            } else {
                c
            }
        })
        .collect()
}

fn main() {
    println!("{}", ucwords("hello world")); // Hello World
}
输出
Hello World

TypeScript v26.13.1

v26.13.1
// 无内置标题大小写——手写状态机
function ucwords(s: string): string {
  let out = "";
  let word_start = true;
  for (const c of s) {
    if (c === " ") {
      word_start = true;
      out += c;
    } else {
      out += word_start ? c.toUpperCase() : c;
      word_start = false;
    }
  }
  return out;
}
console.log(ucwords("hello world")); // Hello World
输出
Hello World

语言差异说明

C:无内置;toupper 状态机手写,参数须转 unsigned char(负数下标是未定义行为)。

C++:无内置;同 C 状态机。

C#:TextInfo.ToTitleCase 最接近(文化相关——示例钉死 InvariantCulture);实测撇号后不大写(mike o'hara → Mike O'hara)、连字符后大写(hello-world → Hello-World)。

Go:无内置;strings.Title 已于 Go 1.18 弃用——状态机手写。

Java:无内置;Apache commons-lang WordUtils 是经典第三方方案。

JavaScript:无内置;状态机或 \b\w 正则手写。

PHP:默认分隔符仅六种空白;撇号、连字符均非词边界(mike o'hara → Mike O'hara),可用第二参数自定义(如 ucwords($s, " '-"));8.2 起只转 ASCII 字母且不再受 setlocale 影响,多字节请用 mb_convert_case 的 MB_CASE_TITLE。

Python:title() 把撇号、连字符都当词边界(mike o'hara → Mike O'Hara)——与 PHP 相反方向的行为差异。

Rust:无内置;char::to_uppercase 可能展开多字符(如 ß → SS),示例取首个字符。

TypeScript:同 JavaScript。