แบบฝึกหัด Rust

Palindrome Check in Rust

Does the text read the same in both directions? Ignore spaces, punctuation and case.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Filtering letters
  • Lower case
  • Comparing with the reverse
level
l0
e1
v2
e3
l4
The first and last letters match, then the next pair.

The same forwards and backwards

A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.

filter keeps only letters and digits and map makes them lower case. eq compares the letters with the same letters in reverse order, without building a second vector. {text:?} prints the text with quotes.

ประเด็นสำคัญ

  1. Keep only letters and digits.
  2. Compare in lower case.
  3. eq compares two iterators item by item.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn is_palindrome(text: &str) -> bool {
    let letters: Vec<char> = text
        .chars()
        .filter(|c| c.is_alphanumeric())
        .map(|c| c.to_ascii_lowercase())
        .collect();
    letters.iter().eq(letters.iter().rev())
}

fn main() {
    for text in ["level", "A man, a plan, a canal: Panama", "Rust"] {
        println!("{text:?} -> {}", is_palindrome(text));
    }
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Rust" -> false

ฝึกฝน

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

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

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

ถัดไป: Word Frequency Counter →

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

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

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