c language two strings cross merge instance

  • 2020-06-23 01:29:58
  • OfStack

I don't need to say any more, just code it!


// Here are two ways to do it 
#include<stdio.h>
#include<string.h>
#define M 20 
void main() 
{ 
 char str1[M],str2[M],newstr[2*M]; 
 int chang1,chang2,i,flag,j; 
 int low,high; 
 printf(" Please enter the first 1 String: \n");
 gets(str1);
 printf(" Please enter the first 2 String: \n");
 gets(str2);
 chang1=strlen(str1);
 chang2=strlen(str2);
 if(chang1<chang2)
 {
 low=chang1;
 high=chang2;
 flag=1;
 } 
 else 
 {
 low=chang2;
 high=chang1;
 flag=0;
 } 
 for(i=0;i<low;i++)// Copy the part of the string that has a small number  
 { 
 newstr[2*i]=str1[i]; 
 newstr[2*i+1]=str2[i]; 
 } 
 for(i=low,j=2*i;i<high;i++)// Copy the extra parts of the string  
 {  
 if(flag)
  newstr[j++]=str2[i]; 
 else 
  newstr[j++]=str1[i]; 
 } 
 newstr[low+high]='\0';// add 1 End marks  
 puts(newstr); 
} 
///////////////////////////////////////////////////
//////////////// This one is simpler than the one above //////////////////
#include<stdio.h>
 
int main()
{
 char s1[20],s2[20],s3[40];
 gets(s1);gets(s2);
 int i=0,j=0;
 while(s1[j]!='\0'&&s2[j]!='\0')
 {
 s3[i++]=s1[j];
 s3[i++]=s2[j++];
 }
 if(s1[j]=='\0')
 {
 while(s2[j]!='\0')
  s3[i++]=s2[j++];
 }
 else
 {
 while(s1[j]!='\0')
  s3[i++]=s1[j++];
 }
 s3[i]='\0';
 puts(s3);
 printf("\n");
 return 0;
}

Related articles: