Shm*_*uel 1 c string palindrome
我正在尝试创建一个程序,该程序检查给定的数组/字符串是否是回文,并且不起作用。该程序仅在每个给定的数组上打印“ 0”,即使在回文上也是如此。
int main()
{
char string[100]= {0};
char stringReverse[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
strcpy(stringReverse , string); // This function copies the scanned array to a new array called "stringReverse"
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// This while reverses the array and insert it to a new array called "stringReverse"
while(firstLetter < lastLetter)
{
temp = stringReverse[firstLetter];
stringReverse[firstLetter] = stringReverse[lastLetter];
stringReverse[lastLetter] = temp;
firstLetter++;
lastLetter--;
}
printf("%s %s", stringReverse, string);
if ( strcmp(stringReverse , string) == 0)
{
printf("1");
}
else
{
printf("0");
}
}
Run Code Online (Sandbox Code Playgroud)
可以说我们实现了一个简单的乐趣
int check_palindrome (const char *s) {
int i,j;
for (i=0,j=strlen(s)-1 ; i<j ; ++i, --j) {
if (s[i] != s[j]) return 0; // Not palindrome
}
return 1; //Palindrome
}
Run Code Online (Sandbox Code Playgroud)
我认为这要简单得多;)
对于有问题的代码:请注意fgets()。它停在第一个'\ n'或EOF中,并保留'\ n'字符。
所以,如果你给雷达为前,结果字符串将是“雷达\ n”,不与匹配“\ nradar”