แบบฝึกหัด 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"));
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
tsuR
olléh
productive fast safe

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Tuples and Arrays →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด