연습 문제 (문자열)

namu·2022년 7월 7일
#include <iostream>

using namespace std;

// 문제1) 문자열 길이를 출력하는 함수
int StrLen(const char* str)
{
	// str이라는 문자열의 길이를 반환
	int count = 0;
	while (str[count] != '\0')
	{
		count++;
	}

	return count;
}

// 문제2) 문자열 복사 함수
void StrCpy(char* dest, const char* src)
{
	while (*src != '\0')
	{
		*dest++ = *src++;
	}

	*dest = '\0';
}

// 문제3) 문자열 덧붙이는 함수
char* StrCat(char* dest, const char* src)
{
	//while (*dest != '\0')
	//{
	//	dest++;
	//}

	//StrCpy(dest, src);

	int len = StrLen(dest);
	StrCpy(&dest[len], src);

	return dest;
}

// 문제4) 두 문자열을 비교하는 함수
int StrCmp(const char* a, const char* b)
{
	while (*a == *b && *a != '\0')
	{
		a++;
		b++;
	}

	if (*a < *b)
	{
		return -1;
	}
	else if (*a > *b)
	{
		return 1;
	}

	return 0;
}

// 문제5) 문자열을 뒤집는 함수
void ReverseStr(char* str)
{
	int f = 0;
	int r = StrLen(str) - 1;
	while (f < r)
	{
		int temp = str[f];
		str[f] = str[r];
		str[r] = temp;

		f++;
		r--;
	}
}

#pragma warning(disable: 4996)

int main()
{
	const int BUF_SIZE = 100;

	char a[BUF_SIZE] = "Hello";
	char b[BUF_SIZE] = "World";

	//int len = StrLen(a);
	//cout << len;
	//StrCpy(b, a);
	//StrCat(a, b);

	//int result = StrCmp(a, b);

	ReverseStr(a);

	return 0;
}
profile
안녕하세요

0개의 댓글