Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ตรวจสอบ Palindrome

Palindrome คือสตริงที่อ่านจากหน้าหลังหรือหลังหน้าได้เหมือนกัน (ไม่คำนึงถึงพิมพ์ใหญ่/เล็ก)

ตัวอย่าง: "Malayalam" → กลับคือ "malayalaM" → เท่ากัน (ignore case)

วิธีการ

  1. แปลงสตริงเป็น char array
  2. ใช้ Array.Reverse() กลับลำดับ
  3. สร้างสตริงใหม่จาก array ที่กลับแล้ว
  4. เปรียบเทียบด้วย Equals() แบบ ignore case

ตัวอย่างโค้ดเต็ม

using System;
namespace palindromecheck {
    class Program {
        static void Main(string[] args) {
            string string1 = "Malayalam";
            char[] ch = string1.ToCharArray();
            Array.Reverse(ch);
            string rev = new string(ch);
            bool isPalindrome = string1.Equals(rev, StringComparison.OrdinalIgnoreCase);
            if (isPalindrome) {
                Console.WriteLine(string1 + " is a Palindrome!");
            } else {
                Console.WriteLine(string1 + " is not a Palindrome!");
            }
            Console.Read();
        }
    }
}

ผลลัพธ์

Malayalam is a Palindrome!

วิธีทางเลือก (LINQ):

bool isPalindrome = str.SequenceEqual(str.Reverse());
// ต้อง using System.Linq; และเปรียบเทียบ case-sensitive