C++兑现C#中split函数
C++实现C#中split函数
请问如何实现split函数,即对字符串aa##bb##cc用分隔符“##”分割后,得到3个字符串,分别为"aa","bb","cc",对aa##bb##用分隔符“##”分割后,得到三个字符串,分别为"aa","bb",""
问题的关键是在情况2中能得到空字符串。而不是只得到"aa","bb"!
------解决方案--------------------
http://blog.****.net/puttytree/article/details/7106957
除了以上方法,我常用boost里面的。
------解决方案--------------------
写个小例子,重定义 whitespace 即可。
末尾存在空字符串儿的问题,可以通过单独的逻辑处理。
请问如何实现split函数,即对字符串aa##bb##cc用分隔符“##”分割后,得到3个字符串,分别为"aa","bb","cc",对aa##bb##用分隔符“##”分割后,得到三个字符串,分别为"aa","bb",""
问题的关键是在情况2中能得到空字符串。而不是只得到"aa","bb"!
------解决方案--------------------
http://blog.****.net/puttytree/article/details/7106957
除了以上方法,我常用boost里面的。
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
using namespace std;
int main( int argc, char** argv )
{
string s = "Hello, the beautiful world!";
vector<string> rs;
boost::split( rs, s, boost::is_any_of( " ,!" ), boost::token_compress_on );
for( vector<string>::iterator it = rs.begin(); it != rs.end(); ++ it )
cout << *it << endl;
return 0;
}
------解决方案--------------------
写个小例子,重定义 whitespace 即可。
末尾存在空字符串儿的问题,可以通过单独的逻辑处理。
#include <cctype>
#include <iostream>
#include <iterator>
#include <locale>
#include <sstream>
#include <vector>
const std::ctype_base::mask* whitespace ()
{
using namespace std;
using ctype = std::ctype<char>;
static std::vector<ctype::mask> table (ctype::classic_table(),ctype::classic_table()+ctype::table_size);
table['#'] = ctype::space;
return &table[0];
}
int main (int,char**)
{
std::string const line("aa##bb##");
std::istringstream buffer(line);
std::locale const locale(buffer.getloc(),new std::ctype<char>(whitespace()));
buffer.imbue(locale);
std::vector<std::string> split;