我正在製作一個函數,它可以反轉字符串並檢查字符串是否是迴文。當我用「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); –