从文本中提取字符串
Extracting string from text
我有一个字符串
My name is bob.I am fine
我想把每个单词和'.'在字符串向量中
如何在 C++ 中使用 getline 来做到这一点?
编辑:
std::vector<std::string> words;
std::string word;
while (cin>> word) {
words.push_back(word);
}
我想要'.'作为我无法做到的不同字符串。
不是最优雅的解决方案,但应该可行
#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;
}
我有一个字符串
My name is bob.I am fine
我想把每个单词和'.'在字符串向量中 如何在 C++ 中使用 getline 来做到这一点?
编辑:
std::vector<std::string> words;
std::string word;
while (cin>> word) {
words.push_back(word);
}
我想要'.'作为我无法做到的不同字符串。
不是最优雅的解决方案,但应该可行
#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;
}