【问题标题】:How to split a string from a vector [duplicate]如何从向量中拆分字符串[重复]
【发布时间】:2016-11-23 05:46:56
【问题描述】:

我的作业如下:

第二步 - 创建一个名为 connections.txt 的文件,格式如下:

Kelp-SeaUrchins
Kelp-SmallFishes

从文件中读取这些名称并将每个字符串分成两个(org1,org2)。现在仅通过打印来测试您的工作。例如:

  cout <<  “pair  =  “ << org1 <<  “ , “ << org2 << endl;

我不确定如何拆分存储在向量中的字符串,使用连字符作为拆分它的标记。我被指示创建自己的函数,例如 int ind(vector(string)orgs, string animal) { return index of animal in orgs.} 或使用 find 函数。

【问题讨论】:

标签: c++ string vector split


【解决方案1】:

这是一种方法...

打开文件:

ifstream file{ "connections.txt", ios_base::in };
if (!file) throw std::exception("failed to open file");

阅读所有行:

vector<string> lines;
for (string line; file >> line;)
    lines.push_back(line);

您可以使用 C++11 中的正则表达式库:

regex pat{ R"(([A-Za-z0-9]+)-([A-Za-z0-9]+))" };
for (auto& line : lines) {
    smatch matches;
    if (regex_match(line, matches, pat))
        cout << "pair = " << matches[1] << ", " << matches[2] << endl;
}

您必须根据自己的需要提出模式。
在这里,它将尝试匹配“至少一个字母数字”,然后是 -,然后是“至少一个字母数字”。 match[0] 将包含整个匹配的字符串。
match[1] 将包含第一个字母数字部分,即您的 org1
match[2] 将包含第二个字母数字部分,即您的 org2
(如果需要,您可以将它们放入变量 org1org2。)


如果 org1 和 org2 不包含任何空格,那么您可以使用另一个技巧。

在每一行中,您可以将 - 替换为空格。(std::replace)。
然后只需使用 stringstreams 来获取您的令牌。


旁注:这只是为了帮助你。你应该自己做功课。

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2012-09-18
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多