c语言 字符串逆序输出

2024-11-12 21:11:25
推荐回答(2个)
回答1:

#include
#include
void main(void)
{
char string1[100],string2[100];
int i, k;
printf("Enter a string:");
gets(string1);

k = strlen(string1);
for (i=0;string1[i]!='\0';i++)
{
string2[i]=string1[k-1-i];
}
string2[i] = '\0';
printf("Output:");
printf("%s",string2);
}

优化一下:
#include
#include
void main(void)
{
char string[100];
int i, j, k;
char t;
printf("Enter a string:");
gets(string);

k = strlen(string);
j = k/2;
for (i=0;i {
t = string[i];
string[i] = string[k-1-i];
string[k-1-i] = t;
}
string[k] = '\0';
printf("Output:");
printf("%s",string2);
}

回答2:

在string2的结尾加上一个'\0'
string2[...] = '\0'