我正在制作一个函数,它可以反转字符串并检查字符串是否是回文。当我用“abba”等明显的回文测试函数时,函数表示它不是回文。前向串和反向串的串长也不同!C:回文:不同的strlen值
#include <stdio.h>
#include <string.h>
char forward [] = "abba"; //The string to be reversed
int size = (sizeof(forward)/sizeof(forward[0]) - 1);
int j = 0;
char reverse [10];
void reverser(char forward []) {
printf("%s", "String forward: ");
for (int i = 0; i < size; i++) { //Function for printing out the forward string.
printf("%c", forward[i]);
}
printf("\n");
printf("%s", "String reversed: ");
for (int i = size, j = 0; i >= 0; --i, ++j) { //Function for reversing the string and printing it.
reverse[j] = forward[i];
printf("%c", reverse[j]);
}
printf("\n");
if (strcmp(forward, reverse) != 0) { //Using strcmp to check if the forward and reversed string are the same.
printf("Not a palindrome!\n");
}
else{
printf("A palindrome!\n");
}
printf("Forward string length: %d\n",strlen(forward));
printf("Reversed string length: %d\n",strlen(reverse));
}
int main() {
reverser(forward);
}
输出:
字符串前锋:ABBA
字符串逆转:ABBA
不是回文!
正向字符串长度:9
反转字符串长度:0
请正确缩进您的代码,我无法理解它。 –
'int i = size' - >'int i = size-1' – BLUEPIXY
这是什么?为什么不在strlen()这里? int size =(sizeof(forward)/ sizeof(forward [0]) - 1); –