【问题标题】:Extracting string from text [closed]从文本中提取字符串[关闭]
【发布时间】:2016-07-31 01:45:20
【问题描述】:

我有一个字符串

My name is bob.I am fine

我想把每个单词和'.'在字符串向量中 如何在 C++ 中使用 getline 来做到这一点?

编辑:

std::vector<std::string> words;
std::string word;
while (cin>> word) {
    words.push_back(word);
}

我想要“。”作为我无法做到的不同字符串。

【问题讨论】:

  • 看起来像一个家庭作业问题。请看[what ]在这里提出一个好问题
  • 这与 SO 无关。有关主题的列表,请参阅 How to Ask

标签: c++ c++11 stl programming-languages


【解决方案1】:

不是最优雅的解决方案,但这应该可行

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter)
{
    vector<string> internal;
    stringstream ss(str); 
    string tok;

    while(getline(ss, tok, delimiter))
    {
        internal.push_back(tok);
    }

    return internal;
}

int main(int argc, char **argv)
{

    string str = "My name is bob.I am fine";
    for(int i = 0; i < str.length(); i++)
    {
        if(str[i] == '.')
        {
            str.insert(i++," ");
            str.insert(++i," ");
        }
    }
    vector<string> sep = split(str, ' ');


    for(string t : sep)
        cout << t << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2015-10-04
    • 2012-02-25
    • 1970-01-01
    相关资源
    最近更新 更多