函数功能是首先把b指向的字符串逆向存放
然后将a指向的字符串和b指向的字符串按排列顺序交叉合并到c指向的数组中
两个字符串中过长的剩余字符接在c指向数组的尾部。
分析:主要是交叉合并到c的处理代码如下。
下面是代码实现:
/********************************************************************
编写函数void change(char *a,char *b,char*c)。
函数功能是首先把b指向的字符串逆向存放
然后将a指向的字符串和b指向的字符串按排列顺序交叉合并到c指向的数组中
两个字符串中过长的剩余字符接在c指向数组的尾部。
*********************************************************************/
#include <stdio.h>
#include <stdlib.h>
int mystrlen (char *str) //字符串的长度
{
int length = 0;
if (str == NULL)
{
return -1;
}
while (*str++)
{
length++;
}
return length;
}
void RevStr (char *str, int len)
{
int i = 0;
char temp = 0;
for (i = 0; i < len / 2; i++) //字符串倒置
{
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
void change (char *a, char *b, char *c)
{
int i = 0;
int count = 0;
int blen = mystrlen(b);
RevStr(b, blen); //将字符串b倒置
while (*a)
//遍历a字符串,将a中元素装进c里面
{
*c++ = *a;
if (count < blen)
{
*c++ = *b++;
//交叉放入c中,a长则把a多余的放入c中,否则把b多余的放入c中
count++;
}
a++;
}
while (*b)
{
*c++ = *b++;
}
*c = '\0';
}
int main()
{
char *a = NULL;
char *b = NULL;
char *c = NULL;
a = (char *)malloc(100 * sizeof(char));
b = (char *)malloc(100 * sizeof(char));
c = (char *)malloc(100 * sizeof(char));
printf ("Please input a string: "); //接收2个字符串
scanf ("%s", a);
printf ("Please input a string: ");
scanf ("%s", b);
change(a, b, c);
printf ("c = %s\n", c); //输出结果
free(c);
c = NULL;
free(b);
b = NULL;
free(a);
a = NULL;
return 0;
}