Write a program to merge two string alternatively in c

20 Sep 2022 Balmiki Mandal 0 C Programming

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:

  1. Declare three character arrays str1, str2, and result.
  2. Read in the two input strings str1 and str2.
  3. Initialize three integer variables i, j, and k to 0.
  4. While str1[i] and str2[j] are not null characters:
    • Copy str1[i] to result[k].
    • Increment i and k.
    • If str2[j] is not a null character, copy str2[j] to result[k].
    • Increment j and k.
  5. Copy any remaining characters in str1 to the end of result.
  6. Copy any remaining characters in str2 to the end of result.
  7. Terminate the result string with a null character.
  8. 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:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

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!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.