【问题标题】: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);
}
我想要“。”作为我无法做到的不同字符串。
【问题讨论】:
标签:
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;
}