函数返回回文的中间字母或字母
本文关键字:中间 返回 回文 函数 | 更新日期: 2023-09-27 18:10:03
我正在编写一个函数来测试字符串是否为回文,我想知道如果字符串确实是回文,如何返回中间字母或字母?
这是我到目前为止所做的:
检查字符串是否为回文的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
被枚举了两次,这可能是一件坏事
试试这个:
private static string GetMiddleLetters(string input)
{
//Find the middle point
var mid = input.Length / 2.0;
//If it's odd, we take 1 letter, if it's even, we take 2
var numToTake = (mid == (int)mid) ? 2 : 1;
//Round up from the middle, and subtract one (as Substring is 0-indexed)
var startIndex = (int)Math.Ceiling(mid) - 1;
return input.Substring((int)Math.Ceiling(mid) - 1, numToTake);
}
并像这样使用:
var fixedString = myRegex.Replace(userInput, string.Empty).ToLower();
if (IsPalindrome(fixedString))
{
Console.WriteLine(GetMiddleLetters(fixedString));
//Rest of the code here...
}
像这样:
public static String MiddleLetters(string value) {
if (String.IsNullOrEmpty(value))
return value; // middle of the "null" is supposed to be null
return value.Length % 2 == 0 ?
value.Substring(value.Length / 2 - 1, 2)
: value.Substring(value.Length / 2, 1);
}
测试是否为回文:
public static bool IsPalindrome(string value) {
if (String.IsNullOrEmpty(value))
return true; // or false, or throw an exception
//TODO: are you looking for case sensitive or case insensitive palindromes?
for (int i = 0; i < value.Length / 2; ++i)
if (value[i] != value[value.Length - i - 1])
return false;
return true;
}