我有一个std::string s=n8Name4Surname
。 我怎样才能得到两个string名称和姓氏? 谢谢
一种方法是使用Boost.Tokenizer
。 看到这个例子:
#include <string> #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> int main() { using namespace std; using namespace boost; string text="n8Name4Surname."; char_separator<char> sep("0123456789"); tokenizer<char_separator<char> > tokens(text, sep); string name, surname; int count = 0; BOOST_FOREACH(const string& s, tokens) { if(count == 1) { name = s; } if(count == 2) { surname = s; } ++count; } }
编辑
如果你把结果放在一个vector
,它的代码更少:
#include <string> #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <algorithm> #include <iterator> #include <vector> int main() { using namespace std; using namespace boost; string text="n8Name4Surname."; char_separator<char> sep("0123456789"); tokenizer<char_separator<char> > tokens(text, sep); vector<string> names; tokenizer<char_separator<char> >::iterator iter = tokens.begin(); ++iter; if(iter != tokens.end()) { copy(iter, tokens.end(), back_inserter(names)); } }
您可以使用函数isdigit(mystring.at(position)
检测字符串中的数字字符,然后提取这些位置之间的子字符串。
看到:
使用数字0-9作为分隔符的Boost标记器 。 然后,扔掉包含“n”的字符串。 这是过火,我意识到…
简单的STL方法:
#include <string> #include <vector> #include <iostream> int main() { std::string s= "n8Name4Surname"; std::vector<std::string> parts; const char digits[] = "0123456789"; std::string::size_type from=0, to=std::string::npos; do { from = s.find_first_of(digits, from); if (std::string::npos != from) from = s.find_first_not_of(digits, from); if (std::string::npos != from) { to = s.find_first_of(digits, from); if (std::string::npos == to) parts.push_back(s.substr(from)); else parts.push_back(s.substr(from, to-from)); from = to; // could be npos } } while (std::string::npos != from); for (int i=0; i<parts.size(); i++) std::cout << i << ":\t" << parts[i] << std::endl; return 0; }
强制性提升精神样本:
#include <string> #include <boost/spirit/include/qi.hpp> #include <iostream> int main() { std::string s= "n8Name4Surname"; std::string::const_iterator b(s.begin()), e(s.end()); std::string ignore, name, surname; using namespace boost::spirit::qi; rule<std::string::const_iterator, space_type, char()> digit = char_("0123456789"), other = (char_ - digit); if (phrase_parse(b, e, *other >> +digit >> +other >> +digit >> +other, space, ignore, ignore, name, ignore, surname)) { std::cout << "name = " << name << std::endl; std::cout << "surname = " << surname << std::endl; } return 0; }