基于std::string的字符串处理

来源:互联网 发布:管家婆软件好不好用 编辑:程序博客网 时间:2024/06/06 00:02

C++标准模板库std使用广泛。该库中处理字符串的对象为std::string,该对象常用来对字符串分割、替换、提取子字符串等操作。但是由于该库全部使用模板编程,而且函数形式也比较复杂,在使用时经常出现问题。为了便于重用,根据在实际使用时常用到的功能,这里将相应的代码集成到了一个文件中,代码如下:

/********************************************************************************************** 文件:StringLib* 功能:基于的std::string实现的常用字符串操作,字符串分割,替换等* 实现:字符串分割,字符串替换,提取文件路径,文件名字,文件扩展名*********************************************************************************************/

#ifndef   _StringLib_h#define   _StringLib_h

#include <string>using namespace std;

#ifdef _cplusplusextern "C" {#endif

//从字符串str中,使用pattern进行分割,并存储到strVec中boolStringSplit(std::string src, std::string pattern, std::vector<std::string>& strVec){ std::string::size_type pos;    src +=pattern;//扩展字符串以方便操作    int size=src.size();  for(int i=0; i<size; i++) {   pos = src.find(pattern,i);   if(pos<size)   {   std::string s=src.substr(i,pos-i);   strVec.push_back(s);   i=pos+pattern.size()-1;   } }

 return true;}

//将字符串str中的所有target字符串替换为replacementbool StringReplace(std::string& src, std::string target, std::string replacement){ std::string::size_type startpos = 0;   while (startpos!= std::string::npos)   {    startpos = src.find(target);   //找到'.'的位置     if( startpos != std::string::npos ) //std::string::npos表示没有找到该字符     {      src.replace(startpos,1,replacement); //实施替换,注意后面一定要用""引起来,表示字符串     }   } 

 return true;}

//提取路径中的文件名字(带路径,不带扩展名)//substr字符串中,第一个参数为截取的位置,第二个为截取的长度std::stringStringGetFullFileName(std::string path){ return path.substr(0, path.rfind('.') == std::string::npos ? path.length() : path.rfind('.') );}

//提取路径中的文件名字std::stringStringGetFileName(std::string path){ StringReplace(path, "/", "\\"); std::string::size_type startpos = path.rfind('\\') == std::string::npos ? path.length() : path.rfind('\\')+1; std::string::size_type endpos   = path.rfind('.') == std::string::npos ? path.length() : path.rfind('.');

 return path.substr(startpos, endpos-startpos);}

//提取路径中文件名字(带扩展名)std::stringStringGetFileNameWithExt(std::string path){ StringReplace(path, "/", "\\"); std::string::size_type startpos = path.rfind('\\') == std::string::npos ? path.length() : path.rfind('\\')+1; return path.substr(startpos);}

//提取路径中的文件路径std::stringStringGetDirectory(std::string path){ StringReplace(path, "/", "\\"); return path.substr(0, path.rfind('\\') == std::string::npos ? path.length() : path.rfind('\\') );}

//提取路径中的文件类型std::string StringGetFileExt(std::string path){ StringReplace(path, "/", "\\"); return path.substr(path.rfind('.') == std::string::npos ? path.length() : path.rfind('.')+1 );}

#ifdef _cplusplus}#endif

#endif

原文地址为 http://zxdflyer.blog.163.com/blog/static/25664262201322510217495/

0 0