Rust 練習問題

Reverse a String in Rust

Reverse characters and words correctly, including letters like é.

  • 初級
  • 約2分で読めます
  • 実行できるサンプル 1 件
学べること
  • chars().rev()
  • collect into a String
  • Reversing words
reverse("Rust")
  1. 1chars()R u s t
  2. 2rev()t s u R
  3. 3collect()"tsuR"

Reverse characters, not bytes

Rust strings are UTF-8, so one character can take more than one byte. Reversing by characters with chars keeps letters such as é intact.

chars gives the characters one by one, rev reverses their order and collect builds a new String. split_whitespace does the same for words, and join puts them back together with spaces.

重要なポイント

  1. A character can take more than one byte.
  2. chars gives whole characters.
  3. collect builds the new String.

実行できる Rust のサンプル

Rust
コードを実行 →
main.rs
fn reverse(text: &str) -> String {
    text.chars().rev().collect()
}

fn reverse_words(text: &str) -> String {
    text.split_whitespace().rev().collect::<Vec<&str>>().join(" ")
}

fn main() {
    println!("{}", reverse("Rust"));
    println!("{}", reverse("héllo"));
    println!("{}", reverse_words("safe fast productive"));
}
この例の実行ボタンを作成 実行結果
tsuR
olléh
productive fast safe

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Tuples and Arrays →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ