[英]Ignoring white space in palindrome
我正在编写一个程序来检查单词是否是回文。 该程序本身可以工作,但是当我输入这一行特定文本“太糟糕了-我隐藏了启动程序”时,它将不会选择并忽略空格和连字符。
我看了以前的问题,但找不到答案。
我的Regex.Replace
错误吗?
string s, revs = "";
Console.WriteLine("Please Enter Word");
s = Console.ReadLine();
string r = Regex.Replace(s , @"[^-\s]", "");
for (int i = s.Length-1; i >= 0; i--)
{
revs += s[i].ToString();
}
if (revs == s)
{
Console.WriteLine("Entered string is palindrome \n String was {0} and reverse string was {1}", s, revs);
}
else
{
Console.WriteLine("String entered was not palindrome.");
}
Console.ReadKey();
您的代码包含两个错误:
@"(\\s|-)"
替换了您要删除的所有字符 考虑到这一点,正确的代码应为:
string s, revs = "";
Console.WriteLine("Please Enter Word");
s = Console.ReadLine();
string r = Regex.Replace(s , @"(\s|-)", "");
for (int i = r.Length-1; i >= 0; i--)
{
revs += r[i].ToString();
}
if (revs == r)
{
Console.WriteLine("Entered string is palindrome \n String was {0} and reverse string was {1}", s, revs);
}
else
{
Console.WriteLine("String entered was not palindrome.");
}
Console.ReadKey();
除了第一个WriteLine
之外,您应该在其中决定要打印的内容(因为revs不再包含空格和连字符了)。
或者,如果您只想使用String.Replace
,则可以通过以下方式两次使用它:
s=s.Replace(' ','');
s=s.Replace('-','');
您正在将Regex.Replace
调用的结果分配给string r
,并且从不引用它。 这就是为什么您的比较失败的原因。
更清楚地说:您正在删除空格,并将该乘积引用为string r
但仅对string s
进行了反转和测试。
Saverio还指出,您的正则表达式将无法正常工作(我自己并未对此进行测试)。
你有:
string r = Regex.Replace(s , @"[^-\s]", "");
for (int i = s.Length-1; i >= 0; i--)
{
revs += s[i].ToString();
}
就在那儿,您应该迭代和反转r
而不是s
因为s
仍然具有所有空白。
而且,正如Saverio所说的,为什么不只是更换?
string r = s.Replace(" ", string.Empty).Reverse();
我没有尝试编译它,但前提是您没有使用应该工作的非常旧的.NET框架。 可能需要using System.Linq
才能使用Reverse()
扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.