如何使用 C# 检查字符串是否为回文?
csharpprogrammingserver side programming更新于 2025/5/26 4:07:17
假设我们需要确定以下字符串是否为回文 −
str = "Level";
为此,将字符串转换为字符数组以检查每个字符 −
char[] ch = str.ToCharArray();
现在找到反向 −
Array.Reverse(ch);
使用Equals方法判断反向是否等于原数组 −
bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);
以下为完整代码 −
示例
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str, rev;
str = "Level";
char[] ch = str.ToCharArray();
Array.Reverse(ch);
rev = new string(ch);
bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);
if (res == true) {
Console.WriteLine("String " + str + " is a Palindrome!");
} else {
Console.WriteLine("String " + str + " is not a Palindrome!");
}
Console.Read();
}
}
}
输出
String Level is a Palindrome!

