编写一个函数char *link(char *s1,char *s2),实现字符串s1与s2的交叉连接,连接后得到的新字符串放在s1中,函数返回值为字符数组s1的首地址。请
#include
#include
int main( )
{char a[100],b[100];
char *link(char *,char *);
gets(a);
gets(b);
此处请写出link函数的调用过程;
puts(a);
}
char *link(char *s1,char *s2)
{
//将s1与s2所指向的字符串交叉连接,生成的新字符串放在s1所指的数组中
}
例如运行时:代表回车
输入abc12345,输出a1b2c345。
输入abcde123,则输出a1b2c3de。
你在创建一个数组 然后用for循环 把s1 和s2放在这个for循环中同时遍历,取他们两个的每一项值同时存储在新数组中,这样一次遍历后新数组的值就是第一个是s1的第一个值第二个值就是s2的第一个值
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN (100)
char *link(char *s1, char *s2)
{
char buf[MAX_LEN] = { 0 };
int nIndex = 0;
char* temp = s1;
for (; *s1 != '\0' && *s2 != '\0'; ++s1, ++s2)
{
if (nIndex < _countof(buf))
{
buf[nIndex++] = *s1;
}
if (nIndex < _countof(buf))
{
buf[nIndex++] = *s2;
}
}
if (*s1 != '\0')
{
memcpy(buf + nIndex, s1, min(strlen(s1), MAX_LEN - nIndex));
}
else
{
memcpy(buf + nIndex, s2, min(strlen(s2), MAX_LEN - nIndex));
}
memcpy(temp, buf, sizeof(buf));
return temp;
}
int main()
{
char a[MAX_LEN], b[MAX_LEN];
gets_s(a, _countof(a));
gets_s(b, _countof(b));
link(a, b);
puts(a);
return 0;
}
char *link(char *s1,char *s2)
{
//将s1与s2所指向的字符串交叉连接,生成的新字符串放在s1所指的数组中
char *s = s1;
while(*s1)
s1++;
while(*s2)
{
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
return s1 - s;
}
希望能够帮助你