1 minute read

1. 표준 String 클래스

  • C++ 표준 라이브러리에는 string 클래스가 정의되어 있다.
  • 헤더파일 <string>

  • 예제
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
	string str1="I like ";
	string str2="string class";
	string str3=str1+str2;              //operator+ 연산자의 오버로딩으로 덧셈이 가능하다

	cout<<str1<<endl;
	cout<<str2<<endl;
	cout<<str3<<endl;

	str1+=str2;
	if(str1==str3) 	
		cout<<"동일 문자열!"<<endl;
	else
		cout<<"동일하지 않은 문자열!"<<endl;

	string str4;
	cout<<"문자열 입력: ";
	cin>>str4;
	cout<<"입력한 문자열: "<<str4<<endl;
	return 0;
}

/*result
I like
string class
I like string class
동일 문자열!
문자열 입력: Hi~
입력한 문자열: Hi~
*/

2. 문자열 처리 클래스 정의

  • String class 구현해보기

✏️표준 string 분석

  1. 문자열을 인자로 전달받는 생성자가 정의되어 있다
    • ex) string str = "I like" = string str("I like")
  2. 생성자, 소멸자, 복사 생성자, 대입 연산자 정의
    • 저장하고자 하는 문자열 길이가 다르기 때문에 동적할당을 해야한다. 따라서 소멸자도 정의해야하고 깊은 복사를 하는 생성자와 대입연산자도 정의해야 한다.
  3. +연산자 오버로딩
    • s3 = s1 + s2와 같은 연산을 했을때, 반환값으로 주소를 줄 것인지, 아니면 객체를 줄 것인지 정해야한다.
  4. +=연산자 오버로딩
  5. ==연산자 오버로딩
  6. «,»연산자 오버로딩

💻String 클래스 구현

#include <iostream>
#include <cstring>
using namespace std;

class String
{
private:
	int len;
	char * str;
public:
	String();
	String(const char * s);
	String(const String& s);
	~String();
	String& operator= (const String& s);
	String& operator+= (const String& s);
	bool operator== (const String& s);
	String operator+ (const String& s);

	friend ostream& operator<< (ostream& os, const String& s);
	friend istream& operator>> (istream& is, String& s);
};

String::String()
{
	len=0;
	str=NULL;
}

String::String(const char* s)
{
	len=strlen(s)+1;
	str=new char[len];
	strcpy(str, s);
}

String::String(const String& s)
{
	len=s.len;
	str=new char[len];
	strcpy(str, s.str);
}

String::~String() 
{
	if(str!=NULL)
		delete []str; 
}

String& String::operator= (const String& s)
{
	if(str!=NULL)
		delete []str;
	len=s.len;
	str=new char[len];
	strcpy(str, s.str);
	return *this;
}

String& String::operator+= (const String& s)
{
	len+=(s.len-1);
	char* tempstr=new char[len];
	strcpy(tempstr, str);
	strcat(tempstr, s.str);

	if(str!=NULL)
		delete []str;
	str=tempstr;
	return *this;
}

bool String::operator== (const String& s)
{
	return strcmp(str, s.str) ? false : true;
}

String String::operator+ (const String& s)
{
	char* tempstr=new char[len+s.len-1];
	strcpy(tempstr, str);
	strcat(tempstr, s.str);
	
	String temp(tempstr);
	delete []tempstr;
	return temp;
}

ostream& operator<< (ostream& os, const String& s)
{
	os<<s.str;
	return os;
}

istream& operator>> (istream& is, String& s)
{
	char str[100];
	is>>str;
	s=String(str);
	return is;
}

int main(void)
{
	String str1="I like ";
	String str2="string class";
	String str3=str1+str2;

	cout<<str1<<endl;
	cout<<str2<<endl;
	cout<<str3<<endl;

	str1+=str2;
	if(str1==str3) 	
		cout<<"동일 문자열!"<<endl;
	else
		cout<<"동일하지 않은 문자열!"<<endl;

	String str4;
	cout<<"문자열 입력: ";
	cin>>str4;
	cout<<"입력한 문자열: "<<str4<<endl;
	return 0;
}

Tags: ,

Categories:

Updated: