본문 바로가기

C언어/복습

[C언어]DAY13_문자열 응용, 다차원 배열

문자열 응용

 


//문제

//문자열을 선언하고 "Hello World"로 초기화한 뒤,

//문자열에 있는 영문을 모두 소문자로 변환시키는 프로그램을 작성하세요.

// "Hello World" => "hello world"

//대문자와 소문자는 32차이가 난다.

 

#include <stdio.h>
#define MAX 100

void lower(char* arr, int count){
	int i =0;
	printf("%d\n", sizeof(arr));
	for(i=0; i < count; i++){
		if(arr[i] >='A' &&  arr[i] <='Z' ){
			arr[i] += 32;
		}
	}
}

//배열의 각 원소의 제곱을 하는 함수 a이면 100더하기
void square(int* arr4, int count){
	int i = 0;
	for(i = 0; i < count; i++){
		arr4[i] += 100;
		printf("%d\n", arr4+i);
	}
}

int main(){

	//선언 및 초기화
	char arr[] = "Hello World";
	char arr2[] = "It is fine!";
	char arr3[] = "It's a Little Bit Funny";
	int arr4[] = {1, 3, 5, 7};
	
	//배열을 함수의 인자로 보낼 때 배열이름, 배열 크기를 같이 보내야함.
	lower(arr, sizeof(arr)); // char는 1byte이므로 배열사이즈라고 착각할 수 있음.
	lower(arr2, sizeof(arr2));
	lower(arr3, sizeof(arr3));
	printf("%d\n", sizeof(arr4)); //sizeof는 : byte size, 배열사이즈가 아님. 원소의 사이즈로 나눠야 배열사이즈가 나옴.

	square(arr4, sizeof(arr4)/sizeof(int));
	printf("%s\n", arr);
	printf("%s\n", arr2);
	printf("%s\n", arr3);
	printf("%d\n", arr4);
}

 


 

//문자열 안에 있는 특정문자의 갯수를 세는 프로그램을 작성하세요.

//문자열에서 특정 문자를 찾을때 포인터를 이용하세요.

//특정문자는 사용자로부터 입력받으세요.

 

#include <stdio.h>
#define  COL100

int main(){
	int i =0;
	int count = 0;
	char ch = 0;
	
	char text[] = "programming: understanding what happens as the computer runs each line of code.";
	//사용자로부터 문자를 입력받는다.
	//text에 문자의 갯수를 세어서 출력한다.
	//a개수 6.
	
	printf("세고 싶은 문자를 입력하세요.");
	scanf_s("%c",&ch); //scanf에서 ch의 값을 변경하기를 바라므로 주소를 넘겨야한다.
	printf("%c가 입력되었습니다\n", ch); //prinf에서는 ch값을 읽기만 하므로 값을 넘기면 된다.

	for( i = 0; i<sizeof(text)/sizeof(char); i++){
		if(text[i] == ch) count++;
	}
	printf("\n문장 %s에서 찾아본 결과,\n", text); //배열은 배열이름(주소)만 보내면 된다. 1byte만 카피되므로 효율적.
	printf("%c갯수는 : %d개입니다.\n",ch, count);
}

다차원 배열

 

//한 반 인원이 5명이고 과목이 3과목인 경우
//1) 학생당 평균을 구하여라.
//2) 그 반의 과목별 평균을 구하는 프로그램을 작성하세요.
// 과목0 과목1 과목2 평균
//학생0 100 40 30
//학생1 80 50 20
//학생2 90 60 30
//학생3 80 80 20
//학생4 90 40 30

 

#include <stdio.h>
#define ROW 5
#define COL 3

int main(){
	int i = 0;
	int j = 0;
	int sum[ROW] = {0,};
	int average = 0;
	int score[ROW][COL] = {{100, 40, 30}, {80, 50 ,20}, {90,60,30}, {80, 80, 20}, {90, 40, 30}};

	//학생의 점수를 출력
	for(i =0; i<ROW; i++){
		for(j=0; j<COL; j++){
			printf("%3d ", score[i][j]);
			sum[i] += score[i][j];
		}
		printf("%3d", sum[i]);
		printf("\n");
	}

	for(i =0; i<ROW; i++){
		printf("%3d\n", sum[i]);
	}
}

//문제: string copy

//copy() function을 작성하시오.

//사용예 : copy(str1,str2) : str2를 str1로 복사

 

#include <stdio.h>
#define MAX 100
//p_str1 ="Hel" p_str2 ="Hello World"

//[]대신 *써서 기능 구현하기!
//void copy(char* p_str1, char* p_str2, int max ) {
//	int i = 0;
//	for (i = 0; i < max; i++) {
//		if(p_str2[i] == 0) break;
//			printf("%d", p_str2[i]);
//			p_str1[i] = p_str2[i];
//
//	}
//	printf("\n");
//}

void copy(char* p_str1, char* p_str2, int max) {
	int i = 0;
	for (i = 0; i < max; i++) {
		if(*(p_str2+i) == 0) break;
			printf("%d", *(p_str2+i));
			*(p_str1+i) = *(p_str2+i);

	}
	printf("\n");
}

int main() {
	char str1[MAX] = "";
	char *p_str1 = "Hello World"; //리터럴(상수)를 가리키는 포인터 변수를 저장하기 위한 4byte만 할당.
	char str2[MAX] = "Hello World"; //배열을 저장하기 위한 max*sizeof(char)만큼의 메모리가 할당.
	printf("str1= %s\n", str1);
	//printf("%s\n", p_str1);
	printf("str2= %s\n", str2);

	copy(str1, str2, MAX);
	//copy(p_str1, str2, MAX); //메모리가 할당되어 있지 않는 상태에서 메모리에 쓰려고 하므로
							 //결과를 예측할 수 없다. (에러임!)
	printf("%s\n", p_str1);
	printf("str1= %s\n", str1);
	printf("str2= %s\n", str2);

	//scanf로 비교하기: 배열과 포인터
	printf("문자열을 입력하세요\n");
	scanf_s("%s", str1);
	printf("str1= %s\n", str1);

	//포인터에 scanf사용하면 에러임. 메모리가 확보(할당) 안되어 있는 상태에서 쓰기를 하므로.
	printf("문자열을 입력하세요\n");
	//scanf_s("%s", p_str1);
	p_str1 = str1;
	scanf_s("%s", p_str1); //포인터가 리터럴을 가리키는 게 아니라. 배열(메모리가 확보되어있는 상태)
							//에서는 잘 동작함.
	printf("p_str1= %s\n", p_str1);
}

 


//문제 : 문자열의 길이를 계산하는 프로그램을 작성하시오.

//char* text = "hello world"

//len(text)를 호출하면 길이를 반환하는 함수를 구현하시오.

 

#include <stdio.h>


int len(char* p_str){
	int count =0;
	for(; *p_str !=0; p_str++){
			count++;
	}
	return count;
}

int main(){
	// ' ' =32, NULL = 0
	char* p_text = "hello world"; //읽기만 하는 용도는 포인터로 선언해도 괜찮다.
								  //쓰거나(변경) 안됌.
	char text[] = "good morning world";

	printf("%d\n", len(text));
	printf("%d\n", len(p_text));

}

------------ 단축키 ------------


F2 : 이름바꾸기

 

---------------------------------