basic_usage/
basic_usage.rs

1/// Basic string width calculation examples
2///
3/// Run with: cargo run --example basic_usage
4use string_width::{
5    AmbiguousWidthTreatment, StringWidthOptions, string_width, string_width_with_options,
6};
7
8fn main() {
9    println!("=== Basic String Width Examples ===\n");
10
11    // Basic ASCII text
12    let text = "Hello, World!";
13    println!("Text: '{}'", text);
14    println!("Width: {}\n", string_width(text));
15
16    // East Asian characters (full-width)
17    let text = "你好世界";
18    println!("Text: '{}'", text);
19    println!("Width: {}\n", string_width(text));
20
21    // Mixed content
22    let text = "Hello 世界!";
23    println!("Text: '{}'", text);
24    println!("Width: {}\n", string_width(text));
25
26    // Emoji examples
27    let text = "Hello 👋 World 🌍";
28    println!("Text: '{}'", text);
29    println!("Width: {}\n", string_width(text));
30
31    // Complex emoji sequences
32    let text = "Family: 👨‍👩‍👧‍👦";
33    println!("Text: '{}'", text);
34    println!("Width: {}\n", string_width(text));
35
36    // Keycap sequences
37    let text = "Numbers: 1️⃣ 2️⃣ 3️⃣";
38    println!("Text: '{}'", text);
39    println!("Width: {}\n", string_width(text));
40
41    // Flag sequences
42    let text = "Flags: 🇺🇸 🇯🇵 🇬🇧";
43    println!("Text: '{}'", text);
44    println!("Width: {}\n", string_width(text));
45
46    // ANSI escape sequences (stripped by default)
47    let text = "\x1b[31mRed text\x1b[0m";
48    println!("Text with ANSI: '{}'", text);
49    println!("Width (ANSI stripped): {}", string_width(text));
50
51    let options = StringWidthOptions {
52        count_ansi: true,
53        ambiguous_width: AmbiguousWidthTreatment::Narrow,
54    };
55    println!(
56        "Width (ANSI counted): {}\n",
57        string_width_with_options(text, options)
58    );
59
60    // Ambiguous width characters
61    let text = "±×÷";
62    println!("Text: '{}'", text);
63    println!("Width (narrow): {}", string_width(text));
64
65    let options = StringWidthOptions {
66        count_ansi: false,
67        ambiguous_width: AmbiguousWidthTreatment::Wide,
68    };
69    println!(
70        "Width (wide): {}\n",
71        string_width_with_options(text, options)
72    );
73
74    // Zero-width characters
75    let text = "a\u{200B}b\u{200C}c";
76    println!("Text with zero-width chars: 'a\\u{{200B}}b\\u{{200C}}c'");
77    println!("Width: {}\n", string_width(text));
78
79    // Combining characters
80    let text = "e\u{0301}"; // e with acute accent
81    println!("Text with combining: 'e\\u{{0301}}'");
82    println!("Width: {}\n", string_width(text));
83}