In rust, how can I get the console ("terminal") width of a character (char
)?
I want the "column width" as displayed in a console. Typically this is found by counting characters in the string; s.chars().count()
. However some Unicode characters are more than one column width wide. Some are "full width" and others are visually large characters that require multiple console columns.
A few examples
fn main() {
// ASCII 'A'
let c: char = '\u{41}';
println!("{:?} len_utf8 {} len_utf16 {} as u128 0x{:08X}", c, c.len_utf8(), c.len_utf16(), c as u128);
// full-width A
let c: char = '\u{FF21}';
println!("{:?} len_utf8 {} len_utf16 {} as u128 0x{:08X}", c, c.len_utf8(), c.len_utf16(), c as u128);
// visually wide char NEW MOON WITH FACE
let c: char = '\u{1F31A}';
println!("{:?} len_utf8 {} len_utf16 {} as u128 0x{:08X}", c, c.len_utf8(), c.len_utf16(), c as u128);
}
Prints
'A' len_utf8 1 len_utf16 1 as u128 0x00000041
'A' len_utf8 3 len_utf16 1 as u128 0x0000FF21
'' len_utf8 4 len_utf16 2 as u128 0x0001F31A
Character 'LATIN CAPITAL LETTER A' A (U+0041) is displayed one console columns wide.
Character 'FULLWIDTH LATIN CAPITAL LETTER A' A (U+FF21) is displayed two console columns wide.
Character 'NEW MOON WITH FACE' (U+1F31A) is displayed three console columns wide.
In rust, how can I find a char
console column width?