我正在编写一个函数来测试字符串是否为回文,我想知道如果字符串确实是回文,如何返回中间字母或字母?
这是我目前所拥有的:
检查字符串是否为回文的 bool 值:
public static bool IsPalindrome(string input)
{
int i = 0;
int j = input.Length - 1;
while (true)
{
if (i > j)
{
return true;
}
char a = input[i];
char b = input[j];
if (!a.Equals(b))
{
return false;
}
i++;
j--;
}
}
这里是我希望能够打印出中间字母的地方:
while (true)
{
Console.Clear();
Regex myRegex = new Regex("[ ;:,.-?'!\"]");
string userInput = String.Empty;
Console.WriteLine("Please enter sentence or phrase");
userInput = Console.ReadLine();
Console.WriteLine();
if (IsPalindrome(myRegex.Replace(userInput, string.Empty).ToLower()))
{
Console.WriteLine("True");
Console.WriteLine("Press any key to continue");
}
else
{
Console.WriteLine("False");
Console.WriteLine("Press any key to continue");
}
Console.ReadLine();
}
最佳答案
这是返回中间字母的另一个实现:
public string MiddleLettersOf(string s)
{
if (s.Length == 0)
return "";
if ((s.Length & 1) == 1) // Odd length?
return s.Substring(s.Length/2, 1);
return s.Substring(s.Length/2-1, 2);
}
(假设传递空字符串是错误的,因此我允许它抛出 NullReferenceException。)
顺便说一句,检查字符串是否为回文的一种简单(但不是最有效)方法是:
public static bool IsPalindrome(string s)
{
return s.SequenceEqual(s.Reverse());
}
您可以将该测试推广到任何 IEnumerable:
public static bool IsPalindrome<T>(IEnumerable<T> s)
{
return s.SequenceEqual(s.Reverse());
}
但该代码的缺陷是 s
被枚举了两次,这可能是一件坏事。
关于c# - 返回中间字母或回文字母的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32221409/