본문 바로가기

C\C++

String 관련 예제

개요

1. 문자열 안에 포함된 특정한 문자의 개수를 세는 함수 int str_chr(char *s, int c)를작성하라.
s는 문자열이고 c는 개수를 셀 문자이다.

목표

실행결과
문자열을 입력하시오: I am a boy
개수를 셀 문자를 입력하시오: a
a의 개수: 2

Code

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

#define INSIZE (unsigned)sizeof

int str_chr(char* s, int c);

int str_chr(char* s, int c)
{
	int cnt = 0;
	for (int i = 0; i <= INSIZE(s); i++) {
		if (s[i] == c) {
			cnt++;
		}
	}
	return cnt;
}

int main(void)
{
	char sInput[20] = { 0 }, cChar=NULL;
	int iCnt=0;

	printf("문자열을 입력하시오 : ");
	gets_s(sInput,INSIZE(sInput));	
	printf("개수를 셀 문자를 입력하시오 : ");
	scanf_s("\n%c", &cChar,INSIZE(char)+1);
	
	iCnt = str_chr(sInput, cChar);
	printf("%c의 개수 : %d", cChar, iCnt);

	return 0;
}

Output

 

 

개요

2. 사용자로부터 받은 문자열에서 각각의 문자가 나타나는 빈도를 계산하여 출력하는 프로그램을 작성하라.

목표

실행결과
문자열을 입력하시오: meet at midnight
a: 1
b: 0
c: 0
e: 2
.......
참고 : 1번에서 작성한 str_chr() 함수를 이용하여 보자.

 

 


Code

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

#define INSIZE (unsigned)sizeof

int str_chr(char* s, int c);

int str_chr(char* s, int c)
{
	int cnt = 0;
	for (int i = 0; i <= INSIZE(s); i++) {
		if (s[i] == c) {
			cnt++;
		}
	}
	return cnt;
}

int main(void)
{
	char sInput[20] = { 0 };

	printf("문자열을 입력하시오 : ");
	gets_s(sInput, INSIZE(sInput));
	puts(" ");
	for (int i = 'a'; i <= 'z'; i++) {
		printf("%c의 갯수 : %d%c", i, str_chr(sInput, i),((i-'a'+1)%5==0)?'\n':'\t');
	}
	return 0;
}

Output

 

개요

3. 다음과 같이 연산의 이름을 문자열로 받아서 해당 연산을 실행하는 프로그램을 작성하라.
연산을 나타내는 문자열은 "add", "sub", "mul", "div" 으로 하라.

목표

연산을 입력하시오: add 3 5
연산의 결과: 8

Code

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

#define INSIZE (unsigned)sizeof

void opResult(char* op, int a, int b)
{
	if (strcmp(op, "add")==0) { printf("%d\n", a + b); }
	else if (strcmp(op, "sub") == 0) { printf("%d\n", a - b); }
	else if (strcmp(op, "mul") == 0) { printf("%d\n", a * b); }
	else if (strcmp(op, "div") == 0) { printf("%.2f\n", (float)a / b); }
	else if (strcmp(op, "exit") == 0) { printf("프로그램 종료."); }
	else printf("\n연산자가 잘못 입력되었습니다.\n");
}

int main(void)
{
	char sOp[10] = { 0 };
	int iX = 0, iY = 0;

	printf("Operater : \"add\",\"sub\",\"mul\",\"div\",\"exit\"\n");
	do {
		printf("연산을 입력하시오 : ");
		scanf_s("%s %d %d", sOp, INSIZE(sOp), &iX, &iY);
		printf("연산의 결과 : ");
		opResult(sOp, iX, iY);
	} while (strcmp(sOp, "exit"));

	return 0;
}

Output

 

'C\C++' 카테고리의 다른 글

구조체 문제  (0) 2022.03.02
최대 최소 구하기(bubble sort)  (0) 2022.02.28
구조체 실습과제 01  (0) 2022.02.23
Structure Input/Output  (0) 2022.02.22
소수 구하기 2  (0) 2022.02.18