본문 바로가기

스터디/코딩

[ 코딩 도장 : C ] Unit 42. 문자열을 복사하고 붙이기 : 연습문제 / 심사문제

42.6 연습문제 : 문자열 포인터를 배열에 복사하기

문제) 다음 소스 코드를 완성하여 "C Language"가 출력되게 만드세요.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main()
{
    char* s1 = "C Language";
    char s2[20];

    strcpy(s2, s1);
    
    printf("%s\n", s2);

    return 0;
}

 

 

42.7 연습문제 : 문자열 포인터를 동적 메모리에 복사하기

문제) 다음 소스 코드를 완성하여 "The Little Prince"가 출력되게 만드세요.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char* s1 = "The Little Prince";
    char* s2 = malloc(sizeof(char) * 20);

    strcpy(s2, s1);

    printf("%s\n", s2);

    free(s2);

    return 0;
}

 

 

42.8 연습문제 : 문자 배열을 붙이기

문제) 다음 소스 코드를 완성하여 "Beethoven 9th Symphony"가 출력되게 만드세요.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main()
{
    char s1[20] = " 9th Symphony";
    char s2[40] = "Beethoven";

    strcat(s2, s1);

    printf("%s\n", s2);

    return 0;
}

 

 

42.9 연습문제 : 문자열 리터럴과 동적 메모리 붙이기

문제) 다음 소스 코드를 완성하여 "Alice in Wonderland"가 출력되게 만드시오.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char* s1 = " Wonderland";
    char* s2 = malloc(sizeof(char) * 30);

    strcpy(s2, "Alice in");
    strcat(s2, s1);
    
    printf("%s\n", s2);

    free(s2);

    return 0;
}

 

 

42.10 심사문제 : 문자 배열 복사하기

문제) 표준 입력으로 길이 30 이하의 어떤 문자열이 입력됩니다. 다음 소스 코드를 완성하여 두 printf가 같은 문자열을 출력하게 만드세요.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main()
{
    char s1[31];
    char s2[31];

    scanf("%s", s1);
    strcpy(s2, s1);

    printf("%s\n", s1);
    printf("%s\n", s2);

    return 0;
}

 

 

42.11 심사문제 : 두 문자열 붙이기

문제) 표준 입력으로 길이 30 이하의 어떤 문자열이 입력됩니다. 다음 소스 코드를 완성하여 입력된 문자열 뒤에 "th"가 붙어서 출력되게 만드세요(scanf 함수 호출 전에 문자열을 출력하면 안 됩니다).

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main()
{
    char s1[40];

    scanf("%s", s1);
    strcat(s1, "th");

    printf("%s\n", s1);

    return 0;
}