【发布时间】:2012-03-19 04:22:32
【问题描述】:
正在开发一个小程序,该程序将从用户那里获取一个字符串并查看它是否是回文。 (一个向后拼写相同的短语,例如“从不奇数或偶数”)我已经构建了从字符串中删除空格和任何非字母字符的函数,然后也复制了字符串。 (所有这三个函数都经过了全面测试,没有问题。)现在我正在研究一个需要比较两个字符串的函数,以查看字符串的前后拼写是否相同。
函数应该通过向前循环主字符串和向后循环并比较每个元素来确定它是否是回文。然而我总是得到一个错误的答案,我做错了什么?
_Bool isPalindrome(char str[], char copy[])
{
int i = 0;
int count = 0, j = 0;
// loop through the main string to find the number of elements
while(str[j] != '\0')
{
count++;
j++;
}
//loop through the main string until the null character.
while(str[i] != '\0')
{
// to loop through the copy backwards,
// use the size of the first and subtract i
size = count - i;
if(str[i] != copy[size])
return FALSE;
i++;
}
return TRUE;
}
【问题讨论】:
-
试试调试器?你的第一个循环也相当于
strlen。 -
用笔和纸以及两个长度为一个字符的输入字符串运行您的代码。看看会发生什么。
标签: c arrays string function boolean