-1

我被告知空字符或 ‍<code>'\0' 用于识别字符串的结尾。

但是,到目前为止,我遇到了两个程序,其中没有使用相同的(空字符)。

所有三个程序都处理strlen(),我无法推断它在这个程序中的重要性和/或存在。

char st[20], rst [20]; // Edit: Added these string declarations!
int i, j;
printf("\n Enter the string : ");
scanf("%s",st);
i= 0;
j = strlen(st) - 1;
while (j >= 0)
{
    rst[i] = st[j];
    i++;
    j--;
}
rst[i] = '\0';
if(strcmp(st, rst) == 0)
    printf("\n %s is a palindrome string", st);
else
    printf("\n %s is not a palindrome string", st);

并且看起来包含或排除空字符不会影响结果。

但是,我很好奇为什么作者会觉得必须添加它。

4

1 回答 1

1

包括空字符保证第二个字符串将以空字符结尾,因此结果是正确的。

即使第二个字符串有可能首先以全零启动,这意味着您不必分配空字符。但是通常当您刚刚分配内存时,您无法预测 st 字符串的内容是什么。

于 2019-09-29T20:49:13.587 回答