gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
How to in Rust get string length in multibyte chars, not in bytes?
- User
How to in Rust get string length in multibyte chars, not in bytes?
- Assistant
In Rust, to get the length of a string in multibyte characters (or more accurately, in Unicode scalar values), you can use the
chars()method on aStringor&str. This method iterates over the string and counts each Unicode scalar value (which can be more than one byte) as a single character.Here’s how you can do it:
rustfn main() { let my_string = String::from("Hello, 世界!"); // Example with multibyte characters // Get the length in characters (Unicode scalar values) let char_length = my_string.chars().count(); println!("The string has {} characters.", char_length); }Explanation
my_string.chars()creates an iterator over the characters of the string..count()consumes the iterator and returns the number of characters.
Notes