1.编写一个函数使字符串逆序:
输入:abcdef
输出:fedcba
法一:递归
#include<stdio.h>
#include<string.h>
void reverse(char* s)
{
int n = strlen(s);
if (n > 1)
{
char c = *s;
*s = *(s + n - 1);
*(s + n - 1) = '\0';
reverse(s + 1);
*(s + n - 1) = c;
}
}
int main()
{
char s[] = "abcdef";
printf("逆置前:%s\n", s);
reverse(s);
printf("逆置后:%s\n", s);
return 0;
}
法二:指针
#include<stdio.h>
#include<string.h>
void reverse(char* s)
{
char* left = s;
char* right = s + strlen(s) - 1;
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main()
{
char s[] = "abcdef";
printf("逆置前:%s\n", s);
reverse(s);
printf("逆置后:%s\n", s);
return 0;
}
2.编写一个函数倒置句子中的单词:
输入:I like beijing.
输出:beijing. like I
法一:常规思想
#include <stdio.h>
#include <string.h>
int main()
{
char a[100] = { 0 };
int len, i, j;
scanf("%s", a);
len = strlen(a);
for (i = len - 1; i >= 0; i--)
{
if (a[i] == ' ')
{
for (j = i + 1; a[j] != '\0' && a[j] != ' '; j++)
printf("%c", a[j]);
printf(" ");
}
}
i = 0;
while (a[i] != ' ')
i++;
for (j = 0; j < i; j++)
printf("%c", a[j]);
}
法二:投机取巧
#include<stdio.h>
void reverse()
{
char a[101];
if (scanf("%s", a) != EOF)
{
reverse();
printf("%s ", a);
}
}
int main()
{
reverse();
return 0;
}