如何分隔字符串并将每个部分存储在不同的向量中

How to I delimit a string and store each part in different vectors

本文关键字:存储 个部 向量 何分隔 分隔 串并 字符串 字符      更新时间:2023-10-16

我有一个有很多行的文本文件,一个例子是

约翰:学生:商业

五月:讲师:数学

鲍勃:学生:数学

如何将它们拆分并存储在不同的向量中,例如:

矢量 1:约翰、梅、鲍勃

向量2:学生、讲师、学生

矢量3:商业、数学、数学

我当前的代码是:

ifstream readDetails(argv[1]);
while (getline (readEvents, line, ':')){
    cout << line << endl;
}

它只拆分字符串,但我想不出任何方法来分离字符串并将它们存储到向量中。

您可以创建向量的向量并使用令牌索引。

如果流有时可以具有较少的令牌,则需要处理这种情况。

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
    const int NUM_TOKENS = 3;
    std::vector<std::vector<std::string>> v(NUM_TOKENS);
    int token = 0;
    std::string str("Mary:Had:Lamb");
    std::istringstream split(str);
    std::string line;
    while (std::getline (split, line, ':')){
        v[token++].push_back(line);
        if ( token == NUM_TOKENS )
            token = 0;
    }
    return 0;
}

这可以使用嵌套向量(又名 2D 向量(和嵌套循环来完成。外循环用于将输入拆分为行,内循环用于拆分每行的标记,这些标记由':'分隔。

#include <string>
#include <sstream>
#include <vector>
int main() 
{
    std::istringstream in{
        "john:student:businessn"
        "may:lecturer:mathn"
        "bob:student:math"
    };
    std::vector< std::vector< std::string > > v{ 3 }; // Number of tokens per line
    std::string line;
    // Loop over the lines
    while( std::getline( in, line ) ) {
        std::istringstream lineStrm{ line };
        // Loop to split the tokens of the current line
        for( auto& col : v ) {
            std::string token;
            std::getline( lineStrm, token, ':' );
            col.push_back( token );
        }
    } 
}

科利鲁的现场演示。

创建字符串向量并相应地存储数据。不使用std::istringstream,你基本上可以利用 String 类附带的substr()find(),因此:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main ()
{
    ifstream inFile("data.txt");
    string line;
    vector<string> vStr1,vStr2, vStr3;
    while( std::getline( inFile, line ) ){
        string::size_type idx1 = line.find(":");
        string::size_type idx2 = line.rfind(":");
        vStr1.push_back(line.substr(0,idx1));
        vStr2.push_back(line.substr(idx1+1,idx2-idx1-1));
        vStr3.push_back(line.substr(idx2+1));   
    }
    cout << "vector1: ";
    for(int i(0); i < vStr1.size(); ++i ){
        cout << vStr1[i] << " "; 
    }
    cout << endl;
    cout << "vector2: ";
    for(int i(0); i < vStr2.size(); ++i ){
        cout << vStr2[i] << " "; 
    }
    cout << endl;
    cout << "vector3: ";
    for(int i(0); i < vStr3.size(); ++i ){
        cout << vStr3[i] << " "; 
    }
    cout << endl;
  return 0;
}

结果是

vector1: john may bob
vector2: student lecturer student
vector3: business math math
相关文章: