printf("ho_tari\n");

String 본문

C++

String

호타리 2023. 8. 31. 15:32

<main.cpp>

#include <iostream>

#include "string.h"



int main()

{

	String s1;

	String s2 = "hello, world";     // String s2("hello");

	String s3 = s2;                 // String s3(s2);

	String s4 = "aaa";

	String s5 = "bbb";             

	

	s1 = s2;

	

	if (s1 == s2)

	{

		std::cout << "s1 and s2 are equal" << std::endl;

	}

	else

	{

		std::cout << "s1 and s2 are not equal" << std::endl;

	}

	

	s1 = s4 + s5;

	

	std::cout << "s1 : " << s1.c_str() << std::endl;

	std::cout << "s1 len : " << s1.size() << std::endl;

	

	std::cout << "s1 : " << s1 << std::endl;

	std::cout << "s2 : " << s2 << std::endl;

	std::cout << "s3 : " << s3 << std::endl;

	std::cout << "s4 : " << s4 << std::endl;

	

	return 0;

}

 

<string.h>

#ifndef STRING_H

#define STRING_H

#include <iostream>



class String {

friend std::ostream& operator<<(std::ostream& out, const String& rhs);



private:

	char *str;

	int len;



public:

	String();

	String(const char *str);

	String(const String& rhs);

	~String();

	

	String& operator=(const String& rhs);

	

	bool operator==(const String& rhs);

	

	const String operator+(const String& rhs);

	

	const char *c_str();

	int size();

	

	

};



#endif

 

<string.cpp>

#include "string.h"

#include <cassert>

#include <cstring>



std::ostream& operator<<(std::ostream& out, const String& rhs)

{

	out << rhs.str;

	

	return out;

}



String::String()

{

	this->str = new char[1];

	assert(this->str );

	

	this->str[0] = '\0';

	this->len = 0;

}



String::String(const char *str)

{

	this->str = new char[strlen(str) + 1];

	assert(this->str );

	

	strcpy(this->str, str);

	this->len = strlen(str);

}



String::String(const String& rhs)

{

	this->str = new char[strlen(rhs.str) + 1];

	assert(this->str );

	

	strcpy(this->str, rhs.str);

	this->len = strlen(rhs.str);

}



String::~String()

{

	delete [] this->str;

}



String& String::operator=(const String& rhs)

{

	delete [] this->str;

	this->str = new char[strlen(rhs.str) + 1];

	assert(this->str );

	

	strcpy(this->str, rhs.str);

	this->len = strlen(rhs.str);

	

	return *this;

}



bool String::operator==(const String& rhs)

{

	return strcmp(this->str, rhs.str) == 0;

}



const String String::operator+(const String& rhs)

{

	char buf[this->len + rhs.len + 1];

	strcpy(buf, this->str);

	strcat(buf, rhs.str);

	

	String result(buf);

	

	return result;

}



const char *String::c_str()

{

	return this->str;

}



int String::size()

{

	return this->len;

}

 

<compile 결과>

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

String2  (0) 2023.09.01
Rational3 (여러연산자)  (0) 2023.08.31
Queue  (0) 2023.08.31
Stack  (0) 2023.08.31
Complex3 (여러연산자)  (0) 2023.08.31