检查一个字符串是否是回文串的 C# 程序
要检查字符串是否为回文串,首先需要使用以下方法查找字符串的逆序:
Array.reverse()
之后,使用 equals() 方法匹配原始字符串与逆序字符串。如果结果为真,则表示字符串是回文串。
示例
让我们尝试完整的示例。此处,我们的字符串为“Malayalam”,逆序后仍为相同的结果。
using System; namespace palindromecheck { class Program { static void Main(string[] args) { string string1, rev; string1 = "Malayalam"; char[] ch = string1.ToCharArray(); Array.Reverse(ch); rev = new string(ch); bool b = string1.Equals(rev, StringComparison.OrdinalIgnoreCase); if (b == true) { Console.WriteLine("" + string1 + " is a Palindrome!"); } else { Console.WriteLine(" " + string1 + " is not a Palindrome!"); } Console.Read(); } } }
输出
Malayalam is a Palindrome!
广告