基于std::string的字符串处理
转自:http://zxdflyer.blog.163.com/blog/static/25664262201322510217495/
C++标准模板库std使用广泛。该库中处理字符串的对象为std::string,该对象常用来对字符串分割、替换、提取子字符串等操作。但是由于该库全部使用模板编程,而且函数形式也比较复杂,在使用时经常出现问题。为了便于重用,根据在实际使用时常用到的功能,我将相应的代码集成到了一个文件中,代码如下:
1 /********************************************************************************************* 2 * 文件:StringLib 3 * 功能:基于的std::string实现的常用字符串操作,字符串分割,替换等 4 * 作者:张晓东* 时间:2012-11-19 5 * 修改:2012-11-19完成初步版本,实现:字符串分割,字符串替换,提取文件路径,文件名字,文件扩展名*********************************************************************************************/ 6 7 #ifndef _StringLib_h 8 #define _StringLib_h 9 #include <string> 10 using namespace std; 11 #ifdef _cplusplusextern "C" 12 { 13 #endif 14 //从字符串str中,使用pattern进行分割,并存储到strVec中 15 boolStringSplit(std::string src, std::string pattern, 16 std::vector<std::string>& strVec) 17 { 18 std::string::size_type pos; 19 src +=pattern;//扩展字符串以方便操作 20 int size=src.size(); 21 for(int i=0; i<size; i++) 22 { 23 pos = src.find(pattern,i); 24 if(pos<size) 25 { 26 std::string s=src.substr(i,pos-i); 27 strVec.push_back(s); 28 i=pos+pattern.size()-1; 29 } 30 } 31 return true; 32 } 33 34 //将字符串str中的所有target字符串替换为replacement 35 bool StringReplace(std::string& src, std::string target, std::string replacement){ 36 std::string::size_type startpos = 0; 37 while (startpos!= std::string::npos) 38 { 39 startpos = src.find(target);//找到'.'的位置 40 if( startpos != std::string::npos ) //std::string::npos表示没有找到该字符 41 { 42 src.replace(startpos,1,replacement); //实施替换,注意后面一定要用""引起来,表示字符串 43 } 44 } 45 return true; 46 } 47 48 //提取路径中的文件名字(带路径,不带扩展名) 49 //substr字符串中,第一个参数为截取的位置,第二个为截取的长度std::stringStringGetFullFileName(std::string path) 50 { 51 return path.substr(0, path.rfind('.') == std::string::npos ? path.length() : path.rfind('.') );} 52 //提取路径中的文件名字 53 std::string StringGetFileName(std::string path) 54 { StringReplace(path, "/", "\\"); 55 std::string::size_type startpos = path.rfind('\\') == std::string::npos ? path.length() : path.rfind('\\')+1; 56 std::string::size_type endpos = path.rfind('.') == std::string::npos ? path.length() : path.rfind('.'); 57 return path.substr(startpos, endpos-startpos); 58 } 59 60 61 //提取路径中文件名字(带扩展名) 62 std::string StringGetFileNameWithExt(std::string path) 63 { StringReplace(path, "/", "\\"); 64 std::string::size_type startpos = path.rfind('\\') == std::string::npos ? path.length() : path.rfind('\\')+1; 65 return path.substr(startpos); 66 } 67 68 //提取路径中的文件路径 69 std::string StringGetDirectory(std::string path) 70 { StringReplace(path, "/", "\\"); 71 return path.substr(0, path.rfind('\\') == std::string::npos ? path.length() : path.rfind('\\') ); 72 } 73 74 //提取路径中的文件类型 75 std::string StringGetFileExt(std::string path) 76 { StringReplace(path, "/", "\\"); 77 return path.substr(path.rfind('.') == std::string::npos ? path.length() : path.rfind('.')+1 ); 78 } 79 #ifdef _cplusplus 80 } 81 #endif 82 #endif
既然选择了远方,就不顾风雨兼程