Creative Code

main.c(문자열 라이브러리) 본문

C Programming

main.c(문자열 라이브러리)

빛하루 2023. 8. 7. 15:55

※main.c파일

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


int main(void)
{
	char title1[] = "wonderful tonight";
	int len = my_strlen(title1); // 문자열의 길이
	printf("len : %d\n", len); //메모리에 할당된 공간은 18바이트지만 문자열의 길이는 17바이트로 출력
	
	char title2[my_strlen(title1)+1];
	my_strcpy(title2,title1); //문자열 복사
	
	if (my_strcmp(title1,title2) == 0 ) {  // 문자열 비교  결과가 0이면 같음
		printf("title1 and title2 are equal\n");
	} else {
		printf("title1 and rtitle2 are not equal\n");
	}
	
	char result[100];
	my_strcpy(result,title1);    
	my_strcat(result," - ");     // 문자열 합치기
	my_strcat(result, "eric clapton");
	
	printf("result : %s\n",result);
	return 0;
}

※string.h 파일

#ifndef STRING_H
#define STRING_H

int my_strlen(const char *str);
int my_strcmp(const char *str1,const char *str2);
void my_strcpy(char *str1,const char *str2);
void my_strcat(char *str1,const char *str2);

#endif

※string.c파일

#include <stdio.h>

int my_strlen(const char *str)
{
	int index = 0;
	while (str[index]!='\0') {
		index++;
	}
	return index;
}

int my_strcmp(const char *str1, const char *str2) {
	int result = 0;
	for (int i = 0; i<my_strlen(str1); i++){
		if (str1[i] != str2[i]){
			result = 1;
			break;
		}
	}
	return result;
}

void my_strcpy(char *str1, const char *str2) {
	for (int i = 0; i<=my_strlen(str2); i++){
		str1[i] = str2[i];
	}
}

void my_strcat(char *str1,const char *str2) {
	my_strcpy(str1 + my_strlen(str1),str2);
}