c# - 返回中间字母或回文字母的函数

标签 c#

我正在编写一个函数来测试字符串是否为回文,我想知道如果字符串确实是回文,如何返回中间字母或字母?

这是我目前所拥有的:

检查字符串是否为回文的 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/

相关文章:

c# - 访问器的目的是什么?

c# - 在包含许多对象的大 Canvas 中拖动性能

c# - 为什么 EventArgs 构造函数不 protected ?

c# - 如何在 C# 中合并和更新列表的节点

c# - 如何在 ASP.NET MVC 6 中为不同的环境注册不同的服务?

c# - 快速将数据表映射到模型

c# - 如何将 List 转换为 observablecollection

c# - Exchange FindItem 响应一个项目 ID 和多个项目 ID 的不同属性集

c# linq 更改包含 xml 标签的 xml 元素的值

c# - 我的依赖属性有什么问题?