#include <cstring>
#include "String.h"
/* 생성자 빈객체 생성*/
String::String()
: len(0)
{
buf = new char[1];
buf[0] = '\0';
}
/* 생성자 문자열을 받아서 생성 */
String::String(const char*str) {
len = strlen(str);
buf = new char[len + 1];
strcpy(buf, str);
}
/* 복사생성자 */
String::String(const String &s)
:len(s.len)
{
buf = new char[len + 1];
strcpy(buf, s.buf);
}
/* 소멸자 */
String::~String() {
delete[] buf;
}
/* 대입 연산자 */
String& String::operator=(const String &s) {
len = s.len;
delete[] buf;
buf = new char[len + 1];
strcpy(buf, s.buf);
return *this;
}
/* 문자열 결합 */
String String::operator+(const String &s) {
char *tempStr = new char[len + s.len + 1]; // 문자열 결합할 길이의 임시 문자열 공간 할당
strcpy(tempStr, buf); // 첫번째 문자열 복사
strcat(tempStr, s.buf); // 두번째 문자열 붙이기
String temp(tempStr); // 결합한 문자열로 객체 생성
delete[] tempStr; // 임시 문자열 삭제
return temp;
}
/* 문자열 덧붙이기 */
String& String::operator+=(const String &s) {
len += s.len; // 두 문자열의 길이
char *tempStr = new char[len + 1]; //임시 문자열 할당
strcpy(tempStr, buf); // 원래 문자열 복사
strcat(tempStr, s.buf); // 덧붙일 문자열 붙이기
delete[] buf; // 원래 문자열 소멸
buf = tempStr; // 덧붙인 임시 문자열을 가리킴
return *this;
}
/* 관계연산 */
bool String::operator==(const String &s) {
// 두문자열이 같으면 0을 반환하기 때문에 not 연산을 함
return !strcmp(buf, s.buf);
}
bool String::operator>(const String &s) {
return strcmp(buf, s.buf) > 0;
}
bool String::operator<(const String &s) {
return strcmp(buf, s.buf) < 0;
}
/* 스트림 입력 */
istream& operator>>(istream& is, String& s) {
char temp[255];
is >> temp;
s = String(temp);
return is;
}
/* 첨자 접근 연산 */
char& String::operator[](int idx) {
return buf[idx];
}
// const 객체에서도 접근이 가능하도록 const 함수로 오버로딩
const char& String::operator[](int idx) const {
return buf[idx];
}