Rust 文字列から文字数をカウントする

Rust 文字列から文字数をカウントする

Rustで、文字列から文字数をカウントするサンプルコードを記述してます。「chars()」と「count()」を使用することで可能です。Rustのバージョンは1.66.0を使用してます。

環境

  • OS windows11 home
  • rustc 1.66.0

文字列から文字数をカウント

文字列から文字数をカウントするには「chars()」と「count()」を使用します。

文字列.chars().count()

実際に使用してみます。

fn main() {

    let mut str: String = "abc".to_string();

    println!("{}", str.chars().count()); // 3

    str = "あいうえお".to_string();

    println!("{}", str.chars().count()); // 5

    str = "日本".to_string();

    println!("{}", str.chars().count()); // 2

    str = "😵😻😻".to_string();

    println!("{}", str.chars().count()); // 3

}

実行結果を見ると、取得されていることが確認できます。