How to Get the String Length in Characters in Rust

Created
Modified

Using chars Function

The str::chars() function returns an iterator over the chars of a string slice.

See the following example:

fn main() {
  let mut s = "Hello";
  println!("{}", s.chars().count());

  s = "a̐";
  println!("{}", s.chars().count());
}
5
2

Using unicode-segmentation Crate

Installation

This crate is fully compatible with Cargo. Just add it to your Cargo.toml:

[dependencies]
unicode-segmentation = "1"

unicode-segmentation Usage

use unicode_segmentation::UnicodeSegmentation;

fn main() {
  let mut s = "Hello";
  println!("{}", s.graphemes(true).count());

  s = "a̐";
  println!("{}", s.graphemes(true).count());
}
5
1

Related Tags