본문 바로가기

스터디/코딩

[ 코딩 도장 : C ] Unit 45. 문자열 자르기 : 연습문제 / 심사문제

45.6 연습문제 : 문자열 자르기

문제) 다음 소스 코드를 완성하여 "Alice's", "Adventures", "in", "Wonderland"가 각 줄마다 출력되게 만드세요.

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

int main()
{
    char s1[40] = "Alice's Adventures in Wonderland";

    char* tok = strtok(s1, " ");

    while (tok != NULL)
    {
        printf("%s\n", tok);
        tok = strtok(NULL, " ");
    }

    return 0;
}

 

 

45.7 심사문제 : 문자열 자르기

문제) 표준 입력으로 길이 60 이하의 인터넷 도메인이 입력됩니다. 점을 기준으로 문자열을 분리하여 각 줄마다 출력하세요.

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

int main()
{
	char s1[61];

	scanf("%s", s1);

	char* ptr = strtok(s1, ".");

	while (ptr != NULL)
	{
		printf("%s\n", ptr);
		ptr = strtok(NULL, ".");
	}

	return 0;
}

 

 

45.8 심사문제 : 특정 단어 개수 세기

문제) 표준 입력으로 길이 1,000 이하의 문자열이 입력됩니다. 입력된 문자열에서 "the"의 개수를 출력하는 프로그램을 만드세요(scanf 함수 호출 전에 문자열을 출력하면 안 됩니다). 단, 모든 문자가 소문자인 "the"만 찾으면 되며 "them", "there", "their" 등은 포함하지 않아야 합니다.

scanf에서 공백을 포함한 문자열을 입력받으려면 서식 지정자로 "%[^\n]s"를 사용하면 됩니다.

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

int main()
{
	char s1[1001];
	int num = 0;

	scanf("%[^\n]s", s1);

	char* ptr = strtok(s1, " .,");

	while (ptr != NULL)
	{
		if (ptr != NULL && strcmp(ptr, "the") == 0)
			num += 1;

		ptr = strtok(NULL, " .,");
	}

	printf("%d", num);

	return 0;
}