แบบฝึกหัด Rust
Reverse a String in Rust
Reverse characters and words correctly, including letters like é.
สิ่งที่คุณจะได้เรียนรู้
- 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.
ประเด็นสำคัญ
- A character can take more than one byte.
- chars gives whole characters.
- 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ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด