天天看點

Problem A: 字元串類(I)

Problem A: 字元串類(I)

Description

封裝一個字元串類,用于存儲字元串和處理的相關功能,支援以下操作:

1. STR::STR()構造方法:建立一個空的字元串對象。

2. STR::STR(const char *)構造方法:建立一個字元串對象,串的内容由參數給出。

3. STR::length()方法:傳回字元串的長度。

4. STR::putline()方法:輸出串的内容,并換行。

-----------------------------------------------------------------------------

你設計一個字元串類STR,使得main()函數能夠正确運作。

函數調用格式見append.cc。

append.cc中已給出main()函數。

-----------------------------------------------------------------------------

Invalid Word(禁用單詞)錯誤:“string”、“vector”等被禁用。

Input

輸入有若幹行,每行一個字元串。

Output

每組測試資料對應輸出一行,包含兩部分内容,首先是一個整數,表示輸入串的長度,然後是輸入的字元串,兩者用一個空格分開。格式見sample。

#include <cstdio>
#include <iostream>

using namespace std;

class STR {
private:
    char *s;
    int len;
public:
    STR() {
        len = 0;
    }
    STR(const char *str) {
        int i;
        for (i = 0; str[i] != '\0'; i++);
        len = i;
        s = new char[len + 1];
        for (i = 0; i < len; i++) {
            s[i] = str[i];
        }
        s[len] = '\0';
    }
    int length() { return len; }
    void putline() {
        if (len == 0) cout << endl;
        else cout << s << endl;
    }
    ~STR() {
        if(len) delete[]s;
    }
};



int main()
{
    STR e;
    STR h("Hello World!");
    char s[100001];
    cout << e.length() << " ";
    e.putline();
    cout << h.length() << " ";
    h.putline();
    while(gets(s) != NULL)
    {
        STR str(s);
        cout << str.length() << " ";
        str.putline();
    }
}