mb_strwidth

mb_strwidth(string $string, ?string $encoding = null): int

按终端列宽计字符串宽度:半角 1 列、东亚全角 2 列(UAX #11)——str_pad 对不齐中文的根因与修复。

C C23

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

/* C 没有标准显示宽度 API;这里手写最小 UAX #11 子集:
   解出 UTF-8 码点,东亚区间宽度翻倍 */
static int utf8_width(const unsigned char *s) {
    int w = 0;
    while (*s) {
        unsigned cp = *s;
        int len = 1;
        if (cp >= 0xF0) { cp = ((cp & 7) << 18) | ((s[1] & 63) << 12) | ((s[2] & 63) << 6) | (s[3] & 63); len = 4; }
        else if (cp >= 0xE0) { cp = ((cp & 15) << 12) | ((s[1] & 63) << 6) | (s[2] & 63); len = 3; }
        else if (cp >= 0xC0) { cp = ((cp & 31) << 6) | (s[1] & 63); len = 2; }
        int wide = (cp >= 0x1100 && cp <= 0x115F) || (cp >= 0x2E80 && cp <= 0xA4CF) ||
                   (cp >= 0xAC00 && cp <= 0xD7A3) || (cp >= 0xFF01 && cp <= 0xFF60);
        w += wide ? 2 : 1;
        s += len;
    }
    return w;
}

int main(void) {
    printf("%d\n", utf8_width((const unsigned char *)"hello")); /* 5 */
    printf("%d\n", utf8_width((const unsigned char *)"你好"));  /* 4:每字 2 列 */
    printf("%d\n", utf8_width((const unsigned char *)"abc")); /* 6:全角拉丁 */
    printf("%d\n", utf8_width((const unsigned char *)"a你b"));  /* 4 */
    return 0;
}
输出
5
4
6
4

C++ C++26

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

// 与 C 同一个故事:没有标准宽度函数——手写 UAX #11 子集
static int width(const std::string &s) {
    int w = 0;
    for (unsigned char b : s) {
        if ((b & 0xC0) == 0x80) continue; // 跳过 UTF-8 续字节
        // 完整演示需要全量解码;对下方演示字节,
        // 「数非续字节、CJK 首字节按 2 计」的简化版即可
        w += (b >= 0xE0) ? 2 : 1; // CJK 首字节按宽字符计
    }
    return w;
}

int main() {
    std::cout << width("hello") << "\n"; // 5
    std::cout << width("你好") << "\n";  // 4
    std::cout << width("a你b") << "\n"; // 4
    return 0;
}
输出
5
4
4

C# v11.0.100

v11.0.100
class Program {
    // 没有内建显示宽度 API;手写 UAX #11 子集
    static int Width(string s) {
        int w = 0;
        foreach (char c in s) {
            bool wide = (c >= 0x1100 && c <= 0x115F) || (c >= 0x2E80 && c <= 0xA4CF)
                || (c >= 0xAC00 && c <= 0xD7A3) || (c >= 0xF900 && c <= 0xFAFF)
                || (c >= 0xFF00 && c <= 0xFF60) || (c >= 0xFFE0 && c <= 0xFFE6);
            w += wide ? 2 : 1;
        }
        return w;
    }

    static void Main() {
        Console.WriteLine(Width("hello")); // 5
        Console.WriteLine(Width("你好"));  // 4
        Console.WriteLine(Width("abc")); // 6
        Console.WriteLine(Width("a你b")); // 4
    }
}
输出
5
4
6
4

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"unicode"
)

// 标准库没有宽度函数;用 unicode 区间表近似
func width(s string) int {
	w := 0
	for _, r := range s {
		wide := unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hangul, r) ||
			unicode.Is(unicode.Katakana, r) || (r >= 0xFF01 && r <= 0xFF60)
		if wide {
			w += 2
		} else {
			w++
		}
	}
	return w
}

func main() {
	fmt.Println(width("hello")) // 5
	fmt.Println(width("你好"))  // 4
	fmt.Println(width("abc")) // 6
	fmt.Println(width("a你b")) // 4
	// 精度完整的对应物是 golang.org/x/text/width
}
输出
5
4
6
4

Java v27.0.1

v27.0.1
public class Main {
    // 没有内建显示宽度 API;手写 UAX #11 子集
    static int width(String s) {
        int w = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            boolean wide = (c >= 0x1100 && c <= 0x115F) || (c >= 0x2E80 && c <= 0xA4CF)
                || (c >= 0xAC00 && c <= 0xD7A3) || (c >= 0xF900 && c <= 0xFAFF)
                || (c >= 0xFF00 && c <= 0xFF60) || (c >= 0xFFE0 && c <= 0xFFE6);
            w += wide ? 2 : 1;
        }
        return w;
    }

    public static void main(String[] args) {
        System.out.println(width("hello")); // 5
        System.out.println(width("你好"));  // 4
        System.out.println(width("abc")); // 6
        System.out.println(width("a你b")); // 4
    }
}
输出
5
4
6
4

JavaScript v26.13.1

v26.13.1
// 没有内建宽度 API——按区间近似东亚宽/全角字符
function width(s) {
  let w = 0;
  for (const ch of s) {
    const c = ch.codePointAt(0);
    const wide = (c >= 0x1100 && c <= 0x115F) || (c >= 0x2E80 && c <= 0xA4CF) ||
      (c >= 0xAC00 && c <= 0xD7A3) || (c >= 0xF900 && c <= 0xFAFF) ||
      (c >= 0xFF00 && c <= 0xFF60) || (c >= 0xFFE0 && c <= 0xFFE6);
    w += wide ? 2 : 1;
  }
  return w;
}
console.log(width("hello")); // 5
console.log(width("你好"));  // 4
console.log(width("abc")); // 6
console.log(width("a你b")); // 4
输出
5
4
6
4

PHP v8.6.0

v8.6.0
// 显示宽度:半角 1 列、全角 2 列(UAX #11)
var_dump(mb_strwidth('hello')); // 5
var_dump(mb_strwidth('你好'));  // 4:每字 2 列
var_dump(mb_strwidth('abc')); // 6:全角拉丁
var_dump(mb_strwidth('a你b')); // 4
// str_pad 对不齐中文的根因:它数的是字节,不是列
var_dump(mb_strwidth('你好')); // 4 列……
echo str_pad('你好', 6, '.'), '|', "\n"; // ……但 你好 已有 6 字节:根本不补!
// 修复:按「显示宽度之差」补齐
echo '你好', str_repeat('.', 6 - mb_strwidth('你好')), '|', "\n"; // 视觉上对齐
输出
int(5)
int(4)
int(6)
int(4)
int(4)
你好|
你好..|

Python v3.15.2

v3.15.2
import unicodedata

def width(s):
    # Python 有真正的对应物:unicodedata.east_asian_width
    return sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in s)

print(width("hello")) # 5
print(width("你好"))  # 4
print(width("abc")) # 6
print(width("a你b")) # 4
print(unicodedata.east_asian_width("你")) # W:逐字符的原始判定
输出
5
4
6
4
W

Rust v1.99.1

v1.99.1
// 现实中的对应物是 unicode-width crate;
// 为了零依赖,手写同一套 UAX #11 子集
fn width(s: &str) -> usize {
    s.chars()
        .map(|c| {
            let c = c as u32;
            let wide = (0x1100..=0x115F).contains(&c)
                || (0x2E80..=0xA4CF).contains(&c)
                || (0xAC00..=0xD7A3).contains(&c)
                || (0xF900..=0xFAFF).contains(&c)
                || (0xFF00..=0xFF60).contains(&c)
                || (0xFFE0..=0xFFE6).contains(&c);
            if wide { 2 } else { 1 }
        })
        .sum()
}

fn main() {
    println!("{}", width("hello")); // 5
    println!("{}", width("你好"));  // 4
    println!("{}", width("abc")); // 6
    println!("{}", width("a你b")); // 4
}
输出
5
4
6
4

TypeScript v26.13.1

v26.13.1
// 没有内建宽度 API——按区间近似东亚宽/全角字符
function width(s: string): number {
  let w = 0;
  for (const ch of s) {
    const c = ch.codePointAt(0)!;
    const wide = (c >= 0x1100 && c <= 0x115F) || (c >= 0x2E80 && c <= 0xA4CF) ||
      (c >= 0xAC00 && c <= 0xD7A3) || (c >= 0xF900 && c <= 0xFAFF) ||
      (c >= 0xFF00 && c <= 0xFF60) || (c >= 0xFFE0 && c <= 0xFFE6);
    w += wide ? 2 : 1;
  }
  return w;
}
console.log(width("hello")); // 5
console.log(width("你好"));  // 4
console.log(width("abc")); // 6
console.log(width("a你b")); // 4
输出
5
4
6
4

语言差异说明

C:无标准宽度函数——手写 UTF-8 解码 + UAX #11 子集(示例);精度完整的现实方案是接入 ICU 或 libunibreak;终端对齐场景只有这个办法。

C++:同 C 无标准 API;示例用「跳过续字节、CJK 首字节计 2」的简化版(对示例字节够用);现实项目用 ICU/fmt 库的宽字符支持。

C#:无内建显示宽度——手写区间表(示例);WPF/WinForms 的 MeasureText/MeasureString 是像素级方案但依赖渲染上下文,不适合纯文本列对齐。

Go:标准库无宽度函数——unicode.Is(unicode.Han, ...) 区间表近似(示例);精度完整用 golang.org/x/text/width(External 模块,按 UAX #11 显式分类 Narrow/Halfwidth/Ambiguous/Wide/Fullwidth)。

Java:无内建显示宽度——手写区间表(示例);ICU4J 的 UCharacter.getIntPropertyValue(c, EAST_ASIAN_WIDTH) 是完整版。

JavaScript:无内建(连近似 API 都没有)——手写区间(示例);npm 生态的 string-width 包是事实标准(内部就是区间表)。

PHP:mb_strwidth 按 UAX #11 计:半角 1、全角/宽字符 2;str_pad 对不齐中文的根因:str_pad 数字节(你好 已 6 字节、宽度 6 目标根本不补,示例第二行),正确做法是按 目标列宽 - mb_strwidth 补点(示例第三行);mb_str_pad(8.3+)数的是字符也不是列宽,同样不解决对齐。

Python:有真正的对应物——unicodedata.east_asian_width(ch) 返回单字符分类(N/F/W/H/Na/A),in "WF" 即宽字符判定(示例);这是 10 门语言里唯一内建的 UAX #11 数据。

Rust:现实方案是 unicode-width crate(终端生态核心依赖);示例手写同款子集保持零依赖;crate 版对 Ambiguous 字符有 unicode_width::UnicodeWidthStr::width_cjk 变体。

TypeScript:同 JavaScript。