如何在C ++中检索字符串的第一个单词?
例如,
"abcde fghijk"
我想检索abcde
。另外我该怎么做才能找回fghijk
?有没有方便的功能,或者我应该编写它?
答案 0 :(得分:4)
使用拆分......
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));
答案 1 :(得分:2)
使用stringstreams(<sstream>
标题)
std::string str ="abcde fghijk";
std::istringstream iss(str);
std::string first, second;
iss >> first >> second;
答案 2 :(得分:2)
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
std::vector<std::string> get_words(std::string sentence)
{
std::stringstream ss(sentence);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
return std::vector<std::string>(begin, end);
}
int main() {
std::string s = "abcde fghijk";
std::vector<std::string> vstrings = get_words(s);
//the vector vstrings contains the words, now print them!
std::copy(vstrings.begin(), vstrings.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
输出:
abcde
fghijk