코딩/C언어

두 문자열 결합 (정렬이 되어있다고 가정)

런던전통손만두 2019. 3. 21. 14:02
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
void mergeString(char a[], char b[], char result[])
{
    int i, num1, num2, n1 = 0, n2 = 0;
 
    for (i = 0; a[i] != '\0'; i++);
 
    num1 = i;
 
    for (i = 0; b[i] != '\0'; i++);
 
    num2 = i;
 
    for (i = 0; i <= num1 + num2 + 1; i++)
    {
        if (i == num1 + num2 + 1)
            result[i] = '\0';
        else if (n1 >= num1)
        {
            result[i] = b[n2];
            n2++;
        }
        else if (n2 >= num2)
        {
            result[i] = a[n1];
            n1++;
        }
        else if (a[n1] <= b[n2])
        {
            result[i] = a[n1];
            n1++;
        }
        else if (a[n1] > b[n2])
        {
            result[i] = b[n2];
            n2++;
        }
    }
 
    return;
}
int main(void)
{
    char word1[10], word2[10];
    char mergedWord[20];
 
    scanf("%s %s", word1, word2);
 
    mergeString(word1, word2, mergedWord);
 
    printf("%s\n", mergedWord);
    return 0;
}
cs

 

 

결과:

 

 

반응형