如何使用正则表达式检查字符串是否是回文 [英] How to check whether string is palindrome or not using regular expression

查看:79
本文介绍了如何使用正则表达式检查字符串是否是回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在编写控制台应用程序,它会检查是否是Palindrome。但我不知道如何使用正则表达式,你可以建议相同。也想忽略非字母数字字符。



例如。 Mad& ** am是一个回文





谢谢



< b>我尝试了什么:



static void Main(string [] args)

{

string s,revs =;

Console.WriteLine(请输入字符串值);

s = Console.ReadLine();

for(int i = s.Length - 1; i> = 0; i--)

{

revs + = s [i] .ToString();

}

//字符串检查pallindrome

if(revs == s)

{

Console.WriteLine(字符串是Palindrome \ n输入的字符串是{0}而反向字符串是{1},s,revs);

}

else

{

Console.WriteLine(字符串不是Palindrome \ n输入的字符串是{0}而反向字符串是{1 },s,revs );

}

Console.ReadKey();

}

Hi ,

I am writing console application which will check for word whether it is Palindrome or not. But i dont know how to do it using regular expression can you please suggest for the same. also wanted to ignore none-alphanumeric characters.

Eg. Mad&**am is a palindrome


Thanks

What I have tried:

static void Main(string[] args)
{
string s, revs = "";
Console.WriteLine(" Please Enter a string value");
s = Console.ReadLine();
for (int i = s.Length - 1; i >= 0; i--)
{
revs += s[i].ToString();
}
//string checking for pallindrome
if (revs == s)
{
Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
else
{
Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
Console.ReadKey();
}

推荐答案

甚至不要尝试。

正则表达式绝对是错误的工具。你可以做到,但它会很糟糕。

相反,只需要用C#代码。

完全巧合的是,我昨天为别人写了这篇文章:

Don't even try.
A regex is definitely the wrong tool for that. You could do it, but it'd be horrible.
Instead, just do it in C# code.
By a total coincidence, I wrote this yesterday for someone else:
private static bool IsPalindrome(string inputString)
    {
    char[] inputArray = inputString.ToLowerInvariant().Where(char.IsLetter).ToArray();
    int len = inputArray.Length;
    for (int i = 0; i < len / 2; i++)
        {
        if (inputArray[i] != inputArray[len - (i + 1)]) return false;
        }
    return true;
    }


这篇关于如何使用正则表达式检查字符串是否是回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆