All is well

[YYBASIC0105/얌얌코딩] 간단한 버전의 std::string 클래스 만들어보기 본문

C++/YYBASIC

[YYBASIC0105/얌얌코딩] 간단한 버전의 std::string 클래스 만들어보기

D0YUN 2025. 2. 3. 18:37

`<string>` 라이브러리의 `std::string` 클래스의 `size()` 함수를 이용하면 사용자 정의 함수를 구현하여 문자열 길이를 구할 필요가 없어집니다.

```cpp
//YYBASIC01_05
#include <iostream>
#include <string>
using namespace std;

// 문자열 관련된 것들

class MyString
{
public:
    // 생성자를 이용한 문자열 생성 및 길이 측정
    MyString(const char* str)
    {
        for (int i = 0; i < 256; i++)
            this->str[i] = '\0';

        for (int i = 0; i < 256; i++)
        {
            if (str[i] == '\0')
            {
                len = i;
                break;
            }

            this->str[i] = str[i];
        }
    }

    int size()
    {
        return len;
    }

    // 연산자 오버로딩을 통해 문자열에 문자열 추가하기
    void operator+=(const char* str)
    {
        int idx = 0;
        for (int i = len; i < 256; i++)
        {
            if (str[idx] == '\0')
            {
                len = i;
                break;
            }

            this->str[i] = str[idx++];
        }
    }

    void Print()
    {
        cout << str << " " << len << endl;
    }

private:
    char str[256];
    int len;
};

int main()
{
    string str = "Hello";
    int len = str.size();
    str += " World";

    MyString str2 = "ABCD";
    len = str2.size();
    // 이는 다음과 같음 - MyString str2("ABCD");

    str2.Print();

    str2 += "EFG";
    str2.Print();

    return 0;
}
```

LV01 간단하게 string 클래스 만들어보기