Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A helper function to calculate the width should be used in fmt funcs #9

Open
songzhi opened this issue Mar 10, 2019 · 0 comments
Open

Comments

@songzhi
Copy link

songzhi commented Mar 10, 2019

What Rust std::fmt does:

Acording to this doc,if I want to print some content which is around with spaces,I should write like this.println!("Hello {:5}!", "x");

But actually it has bugs when dealing with like CJK chars.I suppose it is because Rust think width as chars().count().So when I want to print a 10-chars -width line,it actually prints longer.Because CJK-like char counts 1 char but displays 2-chars-width.

What I want:

Here's my solution,It's simple but works:

let total_displayed_width = 10;
let chars_count = "你好".chars().count();
let content_displayed_width = UnicodeWidthStr::width("你好");
let width_in_formatter = total_displayed_width - (content_displayed_width - chars_count);
print!("{}{:^width$}{}", '|', "你好", '|', width = width_in_formatter);
// It prints '|   你好   |',perfectly 10-chars-width

Of course we can do it personally,but I think it is better this crate could provide a func like this.

Jules-Bertholet added a commit to Jules-Bertholet/unicode-width that referenced this issue May 10, 2024
Jules-Bertholet added a commit to Jules-Bertholet/unicode-width that referenced this issue May 10, 2024
Jules-Bertholet added a commit to Jules-Bertholet/unicode-width that referenced this issue May 10, 2024
Jules-Bertholet added a commit to Jules-Bertholet/unicode-width that referenced this issue May 10, 2024
Jules-Bertholet added a commit to Jules-Bertholet/unicode-width that referenced this issue May 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant