Search code examples
cmergestring-concatenation

Merging two strings together in C, switching off characters


I am trying to merge two strings of variable length in C. The result should be 1st character from str1 then 1st character from str2 then 2nd character from str1, 2nd character from str2, etc. When it reaches the end of one string it should append the rest of the other string.

For Example:

str1 = "abcdefg";
str2 = "1234";

outputString = "a1b2c3d4efg";

I'm pretty new to C, my first idea was to convert both strings to arrays then try to iterate through the arrays but I thought there might be an easier method. Sample code would be appreciated.

UPDATE: I've tried to implement the answer below. My function looks like the following.

void strMerge(const char *s1, const char *s2, char *output, unsigned int ccDest)
{
    printf("string1 is %s\n", s1);
    printf("string2 is %s\n", s2);

    while (*s1 != '\0' && *s2 != '\0')
    {
        *output++ = *s1++;
        *output++ = *s2++;
    }
    while (*s1 != '\0')
        *output++ = *s1++;
    while (*s2 != '\0')
        *output++ = *s2++;
    *output = '\0';

    printf("merged string is %s\n", *output);
}

But I get a warning when compiling:

$ gcc -g -std=c99 strmerge.c -o strmerge
strmerge2.c: In function ‘strMerge’:
strmerge2.c:41:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]

And when I run it it doesnt work:

./strmerge abcdefg 12314135
string1 is abcdefg
string2 is 12314135
merged string is (null)

Why does it think argument 2 is an int and how do I fix it to be a char? If I remove the "*" off output in the printf it doesn't give a compile error but the function still doesn’t work.


Solution

  • Your strMerge prints null because, you print the valueAt(*)output which was assigned null the previous step.

    #include<stdio.h>
    #include<string.h>
    //strMerge merges two string as per user requirement
    void strMerge(const char *s1, const char *s2, char *output)
    {
        printf("string1 is %s\n", s1);
        printf("string2 is %s\n", s2);
        while (*s1 != '\0' && *s2 != '\0')
        {
            *output++= *s1++;
        *output++ = *s2++;
        }
        while (*s1 != '\0')
            *output++=*s1++;
        while (*s2 != '\0')
            *output++ = *s2++;
        *output='\0';
    }
    
    int main()
    {
        char *str1="abcdefg"; 
        char *str2="1234";
        char *output=malloc(strlen(str1)+strlen(str2)+1); //allocate memory 7+4+1 = 12 in this case
        strMerge(str1,str2,output); 
        printf("%s",output);
        return 0;
    }
    OUTPUT:
       string1 is abcdefg
       string2 is 1234
       a1b2c3d4efg