본문 바로가기

스터디/코딩

[ 코딩 도장 : C ] Unit 44. 문자열 검색하기 : 연습문제 / 심사문제

44.5 연습문제 : 문자열 안에서 문자로 검색하기

문제) 다음 소스 코드를 완성하여 "n Wonderland", "nderland", "nd"이 각 줄마다 출력되게 만드세요.

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

int main()
{
    char s1[30] = "Alice in Wonderland";

    char* ptr = strchr(s1, 'n');

    while (ptr != NULL)
    {
        printf("%s\n", ptr);
        ptr = strchr(ptr + 1, 'n');
    }

    return 0;
}

 

 

44.6 연습문제 : 문자열의 오른쪽 부터 문자로 검색하기

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

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

int main()
{
    char s1[30] = "The Little Prince";
    char* ptr = strrchr(s1, 'i');

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

    return 0;
}

 

 

44.7 심사문제 : 공백 개수 세기

문제) 표준 입력으로 길이 1,000 이하의 문자열이 입력됩니다. 입력된 문자열에서 공백의 개수를 출력하는 프로그램을 만드세요(scanf 함수 호출 전에 문자열을 출력하면 안 됩니다).

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 = strchr(s1, ' ');

	while (ptr != NULL)
	{
		num += 1;
		ptr = strchr(ptr + 1, ' ');
	}

	printf("%d\n", num);

	return 0;
}