qfedu-c-level/day11/homework/h6.c

33 lines
792 B
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个程序要求用户输入一个字符串然后使用strrev函数将字符串反转并打印反转后的字符串。
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *src)
{
int cnt = 0;
while (src[cnt++])
;
char *res = (char *)malloc(cnt * sizeof(char *));
int tmp = cnt;
for (int i = 0; i < cnt; i++)
{
res[i] = src[tmp - 2]; // tmp - 2 是为了去掉换行符, tmp - 1 是为了去掉字符串末尾的 \0
tmp--;
}
return res;
}
int main()
{
char s1[100];
printf("请输入一个字符串: ");
fgets(s1, sizeof(s1), stdin); // scanf() 不能接收换行,故改用 fgets()
char *s2 = strrev(s1);
printf("反转后的字符串结果为: %s", s2);
free(s2);
return 0;
}