Interleave 2 strings together
This commit is contained in:
parent
f162857633
commit
545f926f0b
|
@ -0,0 +1,46 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
char *interleave(char *str1, size_t len1, char *str2, size_t len2) {
|
||||
char *combined = malloc(len1 + len2 + 1);
|
||||
|
||||
if(!combined) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
char *idx = combined;
|
||||
|
||||
while(*str1 && *str2) {
|
||||
*idx = *str1, *(idx + 1) = *str2;
|
||||
idx += 2, str1 += 1, str2 += 1;
|
||||
}
|
||||
|
||||
char *rest = str1;
|
||||
|
||||
if(*str2) {
|
||||
rest = str2;
|
||||
}
|
||||
|
||||
strcat(idx, rest);
|
||||
return combined;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if(argc != 3) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t len1 = strlen(argv[1]);
|
||||
size_t len2 = strlen(argv[2]);
|
||||
|
||||
char *combined = interleave(argv[1], len1, argv[2], len2);
|
||||
|
||||
if(!combined) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("%s\n", combined);
|
||||
free(combined);
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue