用C语言编程,将两个字符串交叉合并,如将“123”与“abcde”合并为“1a2b3cde"

2025-03-11 04:18:05
推荐回答(1个)
回答1:

#include
#include
//字符串长度
int GetLength(char *str)
{
int i=0;
while(str[i]!='\0')
i++;
return i;
}
//合并字符串
char* Merge(char* first, char* second)
{
int firstLength=GetLength(first);
int secondLength=GetLength(second);

char *result=(char*)malloc(firstLength+secondLength+1);

if(firstLength<=secondLength)
{
int i=0;
for(i=0;i {
result[i*2]=first[i];
}
for(i=0;i {
if(i result[i*2+1]=second[i];
else
result[firstLength*2+i-firstLength]=second[i];
}
}
else
{
int i=0;
for(i=0;i {
result[i*2+1]=second[i];
}
for(i=0;i {
if(i result[i*2]=first[i];
else
result[secondLength*2-1+i-secondLength]=first[i];
}
}
result[firstLength+secondLength]='\0';
return result;
}
//主函数
int main()
{
char* first=(char*)malloc(sizeof(char)*100);
char* second=(char*)malloc(sizeof(char)*100);

printf("please input the first string:");
scanf("%s",first);

printf("please input the second string:");
scanf("%s",second);
getchar();//接收回车

printf("%s",Merge(first,second));
free(first);
free(second);
getchar();//暂停
}