반응형

C언어 문자열 복사

1. 문자 배열 복사

2. strcpy()

 

 

strcpy 없이 - Copy string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Copy string */
#include <stdio.h>
 
int getLength(char str[]) {
    int len = 0;
    for (int i = 0; str[i] != '\0'; i++) len++;
    return len;
}
 
void copy(int len, char strto[], char strfrom[]) {
    for (int i = 0; strfrom[i] != '\0'; i++) strto[i] = strfrom[i];
    strto[len] = '\0';
}
 
int main() {
    char strfrom[] = "Hello world!";
    int len = getLength(strfrom);
    char strto[len];
    copy(len, strto, strfrom);
    printf("%s\n", strto);
}

 

 

 

strcpy()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* Copy strings */
#include <stdio.h>
#include <string.h>
 
int main() {
    char str1[] = "Hello world!\n";
 
    // Get length of array assuming there is a null terminator
    int len = 0;
    for (int i = 0; str1[i] != '\0'; i++) len++;
 
    // Copy from str1 to str2
    char str2[len];
    strcpy(str2, str1);
 
    // Show result
    printf("%s\n", str2);
}

 

 

반응형