c++中istringstream如何分割字符串

1,首先假设

  1. string str = "i am a student";

字符串str必须是使用空格分开的。为了得到各个字串,可以进行按照空格的坐标进行分割,但是可以借助流进行自动分割,如下所示。

istringstream input(str);
string temp;
while(input >> temp){
    cout<<temp<<endl;
}
/*
    output:i
           am
           a
           student
*/

应用:给你一个含有数字的字符串,求所有的数字。

string str = "1 9 10 188 9 122";
istringstream input(str);
string temp;
while(input >> temp){
    cout<<stoi(temp)<<endl;
}

c++如何分割带有逗号的字符串

前提:存在一个字符串,里面有string,int等类型,使用stringstream方法去分割字符串。

#include <vector>
#include <sstream>

vector<string> stu;
string ss;
cin >> ss;

stringstream sstr(ss);
string token;
int be=0;
while(getline(sstr, token, ','))
{
    stu.push_back(token);
}

istringstream和ostringstream的使用方法

• istringstream,由 istream 派生而来,提供读 string 的功能。 (可以将所有类型的数据按字符串读入)
• ostringstream,由 ostream 派生而来,提供写 string 的功能。 (可以将字符串按照他原有的格数输出)
• stringstream,由 iostream 派生而来,提供读写 string 的功能。
要使用上述类,必须包含 sstream 头文件

 #include<iostream>
#include<sstream>
#include<stdio.h>
 using namespace std;

int main()
{
    char str[100],ss[100],w[100];
    while(1)
    {
        gets(ss);
        istringstream str(ss);       //构造一个字符串输入流
        while(str>>w)               //从输入流中 读入一个字符串 遇到空格是结束
            printf("%s\n",w);
    }
    return 0;
}


istringstream input(str);
string val;
vector<TreeNode*> vec;
while (input >> val) {
    cout<<val<<endl;
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode* tmp = q.front();
            q.pop();
            if (tmp) {
                out<<tmp->val<<" "; // 写入
                q.push(tmp->left);
                q.push(tmp->right);
            } else {
                out<<"null ";
            }
        }
        return out.str(); // 转为string
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream input(data);
        string val;
        vector<TreeNode*> vec;
        while (input >> val) {
            if (val == "null") {
                vec.push_back(NULL);
            } else {
                vec.push_back(new TreeNode(stoi(val)));
            }
        }
        int j = 1;                                          // i每往后移动一位,j移动两位,j始终是当前i的左子下标
        for (int i = 0; j < vec.size(); ++i) {              // 肯定是j先到达边界,所以这里判断j < vec.size()
            if (vec[i] == NULL) continue;                   // vec[i]为null时跳过。
            if (j < vec.size()) vec[i]->left = vec[j++];    // 当前j位置为i的左子树
            if (j < vec.size()) vec[i]->right = vec[j++];   // 当前j位置为i的右子树
        }
        return vec[0];
    }

};