Bài tập Rust

Reverse a String in Rust

Reverse characters and words correctly, including letters like é.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

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

Ví dụ Rust chạy được

Rust
Chạy code →
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"));
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
tsuR
olléh
productive fast safe

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Tuples and Arrays →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách