小言_互联网的博客

C++分割字符串的方法

455人阅读  评论(0)

//////////////////////////////////////////////////////////////////////////////////
// 方法一 自定义分割函数 //
//////////////////////////////////////////////////////////////////////////////////

// 定义字符分割函数( 要分割的字符串, 分割后字符串保存到的vector容器, 分隔符) 
void SplitString(const string& s, vector<string>& v, const string& c)
{
  string::size_type pos1, pos2;
  pos2 = s.find(c);                            // 返回分隔符在母串中的位置,如果没找到,返回一个特别的标记值npos 
  pos1 = 0;
  
  while(pos2 != string::npos)                  // 条件:当找到分隔符时 
  {
    v.push_back(s.substr(pos1, pos2-pos1));    // 提取字符串 substr(开始位置, 提取长度) 
 
    pos1 = pos2 + c.size();                    // pos1 变为分隔符位置加上分隔符大小,即下一个字符串起始位  
    pos2 = s.find(c, pos1);                    // find 查找某一位置后分隔符的位置 
  }
  if(pos1 != s.length())                       // 如果 
    v.push_back(s.substr(pos1));
}

///////////////////////////////////////////////////////////////////////////////////
// 方法二 strtok函数 //
///////////////////////////////////////////////////////////////////////////////////

int main() {
	string x = "abcd efgh ijkl";
	char s[100] ;

	// 一定要使用strcpy()函数来操作c_str()返回的指针 
	// c_str() 返回一个const char* 的量,不可以赋给一个可以变更的char*量 
	strcpy(s, x.c_str());                
	char delim[] = " ";

	char *token;
	for(token = strtok(s, delim); token != NULL; token = strtok(NULL, delim)) {
		printf(token);
		printf(",");
	}
	printf("\n");
	return 0;
}

//////////////////////////////////////////////////////////////////////////////////
// 方法三 boost库split函数 //
//////////////////////////////////////////////////////////////////////////////////

boost::split( destination, source, boost::is_any_of( " " ), boost::token_compress_on ); 

//(destination)是用来存储分割的结果的容器
//(source)是要切割的內容
//(boost::is_any_of( " ,!" ))切割条件
// boost::token_compress_on 定义为enum token_compress_mode_type { token_compress_on, token_compress_off };具体用来定义压缩字符空格

转载:https://blog.csdn.net/qq_40432713/article/details/102144910
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场