mb_strwidth

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

Measures string width in terminal columns: halfwidth = 1, East Asian fullwidth = 2 (UAX #11) - the root cause of str_pad failing to align CJK text, and the fix.

C C23

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

/* No standard display-width API in C; a minimal UAX #11 subset that
   decodes UTF-8 code points and doubles the East Asian ranges */
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 columns each */
    printf("%d\n", utf8_width((const unsigned char *)"abc")); /* 6: fullwidth latin */
    printf("%d\n", utf8_width((const unsigned char *)"a你b"));  /* 4 */
    return 0;
}
Output
5
4
6
4

C++ C++26

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

// same story as C: no standard width function - hand-roll the UAX #11 subset
static int width(const std::string &s) {
    int w = 0;
    for (unsigned char b : s) {
        if ((b & 0xC0) == 0x80) continue; // skip UTF-8 continuation bytes
        // full demo needs full decoding; for the demo bytes below the
        // simple "count non-continuation bytes, double CJK lead bytes" suffices
        w += (b >= 0xE0) ? 2 : 1; // CJK lead byte counts as a wide char
    }
    return w;
}

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

C# v11.0.100

v11.0.100
class Program {
    // No built-in display-width API; hand-rolled UAX #11 subset
    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
    }
}
Output
5
4
6
4

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"unicode"
)

// No stdlib width function; approximate with the unicode range tables
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
	// the full-accuracy counterpart is golang.org/x/text/width
}
Output
5
4
6
4

Java v27.0.1

v27.0.1
public class Main {
    // No built-in display-width API; hand-rolled UAX #11 subset
    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
    }
}
Output
5
4
6
4

JavaScript v26.13.1

v26.13.1
// No built-in width API - approximate East Asian Wide/Fullwidth by range
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
Output
5
4
6
4

PHP v8.6.0

v8.6.0
// display width: halfwidth = 1 column, fullwidth = 2 columns (UAX #11)
var_dump(mb_strwidth('hello')); // 5
var_dump(mb_strwidth('你好'));  // 4: 2 columns each
var_dump(mb_strwidth('abc')); // 6: fullwidth latin
var_dump(mb_strwidth('a你b')); // 4
// why str_pad cannot align CJK: it counts BYTES, not columns
var_dump(mb_strwidth('你好')); // 4 columns...
echo str_pad('你好', 6, '.'), '|', "\n"; // ...but it is already 6 BYTES: no pad at all!
// the fix: pad by the difference in DISPLAY width
echo '你好', str_repeat('.', 6 - mb_strwidth('你好')), '|', "\n"; // aligned visually
Output
int(5)
int(4)
int(6)
int(4)
int(4)
你好|
你好..|

Python v3.15.2

v3.15.2
import unicodedata

def width(s):
    # Python has the REAL counterpart: 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: the raw per-char verdict
Output
5
4
6
4
W

Rust v1.99.1

v1.99.1
// the real-world counterpart is the unicode-width crate;
// to stay dependency-free, hand-roll the same UAX #11 subset
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
}
Output
5
4
6
4

TypeScript v26.13.1

v26.13.1
// No built-in width API - approximate East Asian Wide/Fullwidth by range
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
Output
5
4
6
4

Language differences

C: no standard width function - hand-write the UTF-8 decode plus a UAX #11 subset (example); the full-accuracy real-world route is ICU or libunibreak; for terminal alignment this is the only way.

C++: same as C, no standard API; the example uses the simplified "skip continuation bytes, count CJK lead bytes as 2" version (enough for the demo bytes); real projects use ICU or fmt's wide-character support.

C#: no built-in display width - a hand-written range table (example); MeasureText/MeasureString in WPF/WinForms are pixel-level but depend on a rendering context, unsuitable for plain-text column alignment.

Go: the standard library has no width function - a unicode.Is(unicode.Han, ...) range-table approximation (example); for full accuracy use golang.org/x/text/width (an external module that classifies Narrow/Halfwidth/Ambiguous/Wide/Fullwidth per UAX #11).

Java: no built-in display width - a hand-written range table (example); ICU4J's UCharacter.getIntPropertyValue(c, EAST_ASIAN_WIDTH) is the complete version.

JavaScript: no builtin (not even an approximate API) - hand-written ranges (example); the string-width npm package is the de facto standard (it is a range table inside).

PHP: mb_strwidth counts per UAX #11: halfwidth 1, fullwidth/wide 2; THE root cause of str_pad failing to align CJK: str_pad counts bytes (你好 is already 6 bytes, so a target width of 6 pads nothing - the second example line), and the fix is padding by (target columns - mb_strwidth) (the third line); mb_str_pad (8.3+) counts characters, not columns, and equally fails to fix alignment.

Python: THE true counterpart exists - unicodedata.east_asian_width(ch) returns a per-character classification (N/F/W/H/Na/A), and in "WF" is the wide-character test (example); it is the only builtin UAX #11 data among the ten languages.

Rust: the real-world route is the unicode-width crate (a core dependency of the terminal ecosystem); the example hand-rolls the same subset to stay dependency-free; the crate has a width_cjk variant (UnicodeWidthStr::width_cjk) for Ambiguous characters.

TypeScript: same as JavaScript.