C语言问题,求各位牛人帮帮忙,谢谢了!

来源:百度知道 编辑:UC知道 时间:2024/06/04 04:29:38
指向字符串的指针的综合应用
输入一个字符串,字符串中包括3个单词,单词之间以空格分隔,并且第二个单词为and。要求用指向字符串的指针实现交换and两边的单词,并输出交换后的字符串。如:输入字符串为“cat and dog”,则输出的字符串为"dog and cat".

以下是解决方法之一。
输入字符串有3个单词,单词之间以一个空格分隔。
这个约定在 OutExch()中不再检查。

#include <stdio.h>
#include <string.h>

void OutExch(char *str)
{
char ss[80], *s1, *s2;
strcpy(ss, str); //拷贝以保持原始串不变
s1 = strchr(ss, 0x20); //s1指向第一个空格
*s1++ = '\0'; //空格处置0,s1指向and
s2 = strchr(s1, 0x20); //s2指向第二个空格
*s2++ = '\0'; //空格处置0,s2指向后一个单词
printf("\nIN : %s\nOUT: %s %s %s\n", str, s2, s1, ss);
//如果需要改写原字串,可以用下一行语句:
//sprintf(str, "%s %s %s", s2, s1, ss);
}

int main()
{
OutExch("dog and cat");
OutExch("day and night");
OutExch("China and America");
return 0;
}

char * exchange(const char *src)
{
char *dst = (char *)malloc(strlen(src)+1);
*(dst+strlen(src) = '\n';
char *tp = dst;
char *t