Bài tập Rust
Reverse a String in Rust
Reverse characters and words correctly, including letters like é.
Bạn sẽ học được gì
- chars().rev()
- collect into a String
- Reversing words
reverse("Rust")
- 1
chars()R u s t - 2
rev()t s u R - 3
collect()"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
- A character can take more than one byte.
- chars gives whole characters.
- collect builds the new String.
Ví dụ Rust chạy được
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 safeLuyệ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ến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
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