Write a program to merge two string alternatively in c
C Program to Merge Two Strings Alternatively
Merging two strings alternately means combining two strings in a way that the characters from each string alternate in the resulting string. For example, if we merge the strings "abc"
and "def"
, the resulting string would be "adbecf".
Here is an algorithm for merging two strings alternately:
- Declare three character arrays
str1
,str2
, and result. - Read in the two input strings
str1
andstr2.
- Initialize
three
integer variablesi, j
, andk
to0
. - While str1[i] and str2[j] are not null characters:
- Copy
str1[i]
toresult[k].
- Increment
i
andk.
- If
str2[j]
is not anull character,
copy str2[j]
toresult[k]
. - Increment
j
andk
.
- Copy
- Copy any remaining characters in
str1
to theend
of result. - Copy any remaining characters in
str2
to theend
of result. - Terminate the result string with a null character.
- Print the result string.
Note that this algorithm assumes that the two input strings have the same length. If the strings have different lengths, the algorithm will stop merging characters from the longer string once it reaches the end of the shorter string
Write a c program to murge two string alternetvely
#include<stdio.h>
void main()
{
char s1[120],s2[20],s3[40];
int i,j;
printf("Enter first string:");
scanf("%s",s1);
printf("Enter second String:");
scanf("%s",s2);
printf("string1:%s string2:%s\n",s1,s2);
for(i=0,j=0;s1[i]&&s2[i];i++)
{
s3[j++]=s1[i];
s3[j++]=s2[i];
}
if(s1[i])
{
for( ;s1[i];i++)
s3[j++]=s2[i];
}
else if(s2[i])
{
for( ;s2[i];i++)
s3[j++]=s2[i];
}
s3[j]='\0';
printf("s3=%s\n",s3);
for(i=0;s1[i];i++);
}
Output:
Enter first string:abcd
Enter second String:ABCD
string1:abcd string2:ABCD
s3=aAbBcCdD
Top Resources
Write a program to merge two strings alternatively in c
Write a c program to merge two arrays in single array
write a program to merge two string in a single single string.
Further Reading:
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!