I am a C++ dev trying to solve problems in C to practice it, specifically the LeetCode Merge Strings Alternately problem:
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Here is my code. I am looking for critiques from experienced folks out there.
char *mergeAlternately(char *word1, char *word2) {
int len = strlen(word1) + strlen(word2);
bool skip_p1 = false;
bool skip_p2 = false;
char *result =
(char *)malloc(sizeof(char) * (strlen(word1) + strlen(word2) + 1));
char *p1 = word1;
char *p2 = word2;
for (int i;;) {
if (*p1 == '\0') {
skip_p1 = 1;
}
if (*p2 == '\0') {
skip_p2 = 1;
}
if (skip_p1 && skip_p2) {
result[i] = '\0';
return result;
} else if (skip_p1) {
result[i++] = *p2;
p2++;
} else if (skip_p2) {
result[i++] = *p1;
p1++;
} else {
result[i++] = *p1;
p1++;
result[i++] = *p2;
p2++;
}
}
return "SHOULD NEVER REACH HERE";
}
int main() {
char *word1 = "abc";
char *word2 = "pqr";
char *result = mergeAlternately(word1, word2);
printf("Result: %s\n", result);
return 0;
}