2011-06-12 80 views
0

如何在C++中检索字符串的第一个单词?C++检索字符串的一部分

例如,

"abcde fghijk" 

我想找回abcde。我该怎么做才能检索fghijk?有没有一个方便的功能,或者我应该只是编码?

+1

查看http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – 2011-06-12 00:43:41

回答

2

使用stringstreams(<sstream>头)

std::string str ="abcde fghijk"; 
std::istringstream iss(str); 
std::string first, second; 
iss >> first >> second; 
4

使用分裂...

#include <boost/algorithm/string.hpp> 
std::vector<std::string> strs; 
boost::split(strs, "string to split", boost::is_any_of("\t ")); 
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 

在线演示:http://ideone.com/9RjKw