当我运行这个函数时,我没有得到 1 或 0 的返回值。我不知道为什么,我是指针新手,任何类型的帮助/提示将不胜感激。
int isPalindrome (char * str)
{
char def[SIZE];
int length = strlen(str);
for(int count; count <= length; count++ ){
def[count] = str[count];
}
int c;
char *begin, *end, temp;
begin = str;
end = str;
for (c = 0; c < length - 1; c++)
end++;
for (c = 0; c < length/2; c++)
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
for(int count2; count2 <= length; count2++){
if(str[count2] != def[count2]){
return 0;
}
return 1;
}
}
该函数被调用为..
if(isPalindrome(arr) == 1)
printf ("\nIs a palindrome.\n\n");
最佳答案
要检查字符串是否为回文,您需要在首先为所有字符分配足够的空间后,通过循环原始字符串并更改顺序来创建一个反向字符串。然后,您可以使用 strcmp 检查反转后的字符串和原始字符串是否相同。
int isPalindrome (char * str)
{
int length = strlen(str);
char* reversed = malloc(sizeof(char)*length); //we allocate enough space for length chars
for(int i = 0; i < length; i++) {
reversed[i] = str[length-1-i]; //populate reversed with the chars in str but in the reversed order
}
if(strcmp(str,reversed) == 0) //strcmo(a,b) return 0 if they are equal
{
free(reversed); //deallocate the space for reversed
return 1;
}
free(reversed); //deallocate the space for reversed
return 0;
}
关于c - C 中的回文函数,不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634744/