C++流模拟JavaSplit

73 阅读1分钟

C++流模拟JavaStringSplit

在写二叉树序列化和反序列化时,C++并没有直接提供类似Java字符串split这样的字符串分割函数,但是可以用流的思想来模拟该函数。主要涉及的头文件有和。

中的getline函数可以读取整行输入,它的一个构造函数可以读取流中以任意字符分割的token。

image-20250321172427554.png

而中的istringstream可以

istringstream stream(str); // 将字符串包装为输入流

那么结合以上两点,我们就可以写出如下代码:

class serializationAndDeserialiation {
public:
    class Node {
    public:
        int value;
        Node* left;
        Node* right;
​
        Node(int data) : value(data), left(nullptr), right(nullptr) {};
    };
​
    string serialByPre(Node* head) {
        if (head == nullptr) {
            return "#_";
        }
        string res = to_string(head->value) + "_";
        res += serialByPre(head->left);
        res += serialByPre(head->right);
        return res;
    }
​
    Node* deserialByPre(string prestr) {
​
        //C++实现split
        vector<string> tokens;
        istringstream stream(prestr); // 将字符串包装为输入流
        string token;
​
        // 按分隔符读取
        while (getline(stream, token, '_')) {
            tokens.push_back(token);
        }
        return deserialPre(tokens);
    }
​
    Node* deserialPre(vector<string>tokens) {
        if (tokens.empty()) {
            return nullptr;
        }
        string value = tokens.front();
        tokens.erase(tokens.begin());
        if (value == "#") {
            return nullptr;
        }
        //注意new的使用
        /*
        Node* head;
        head  = &Node(stoi(value));
        */
        Node* head = new Node(stoi(value));
        head->left = deserialPre(tokens);
        head->right = deserialPre(tokens);
        return head;
    }
};