-2 c# for-loop palindrome
我是C#的新手,我正在尝试使用简单的isPalindrome方法.基本上我的for循环永远不会进入.我尝试给它字符串"hannah",它永远不会在for循环的主体中打印一个Console.writeline方法调用.但是for循环之前的两个WriteLine调用都为"hannah"返回true,所以它应该进入for循环并从for循环体中打印出至少一个语句.我的循环出了什么问题?
private static Boolean isPalindrome(string s)
{
int counter = 0;
if (s.Length == 1)
{
return true;
}
Console.WriteLine(s[counter]==s[(s.Length - counter - 1)]); //this returns true
Console.WriteLine((counter != (s.Length / 2))); //this returns true
for (; (counter != (s.Length / 2)) & (s[counter] == (s.Length - counter - 1)); counter++)
{
Console.WriteLine("s[counter is {0} and s.length-counter-1 is", s[counter], s[(s.Length - counter - 1)]);
//The above line never prints; why doesn't my for loop get entered?
}
if((counter == (s.Length / 2))) {
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
将你病情的第二部分改为(s[counter] == s[s.Length - counter - 1]).
否则,您将比较s[counter]with的数字表示,而s.Length - counter - 1不是该索引下的字符.