Note that there are some explanatory texts on larger screens.

plurals
  1. POmerging two strings together in C, switching off characters
    primarykey
    data
    text
    <p>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.</p> <p>For Example:</p> <pre><code>str1 = "abcdefg"; str2 = "1234"; outputString = "a1b2c3d4efg"; </code></pre> <p>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.</p> <p><strong>UPDATE:</strong> I've tried to implement the answer below. My function looks like the following.</p> <pre><code>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' &amp;&amp; *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); } </code></pre> <p>But I get a warning when compiling:</p> <pre><code>$ 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] </code></pre> <p>And when I run it it doesnt work:</p> <pre><code>./strmerge abcdefg 12314135 string1 is abcdefg string2 is 12314135 merged string is (null) </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload