首页 > 代码库 > 【工作总结】C++ string工具类

【工作总结】C++ string工具类

工作中在不同的项目中经常对字符串一些特殊处理,比如分隔、比如转码、比如去空格等等,这里整理了一下最近使用的一些字符串操作方法,有些也是从网上搜来的代码,来源已无从查起,所以就不贴来源了。

头文件

  1 /*********************************************  2   *Copyright(C)        zhiqli                       3   *FileName:        StrUtils.h                   4   *Author:            zhiqli  5   *Version:            v1.0  6   *Date:            2014-8-6  7   *Description:        字符串工具类  8   *Platform:        windows 7  9  10   *Others:         11   *History:   12      1.Date:        2014-8-6 13        Author:        zhiqli 14        Modification:创建文件 15 ***********************************************/ 16  17 #ifndef __STR_UTILS_HH__ 18 #define __STR_UTILS_HH__ 19  20 #include <string> 21 #include <vector> 22 #include <algorithm> 23 #include <windows.h> 24  25 using namespace std; 26  27 /********************************************** 28   *Summary: UTF-8转换为GB2312 29   *Parameters: 30        in pUtf8 传入UTF-8字符串 31        out pGb2312 传出GB2312字符串 32   *Return : no 33 ***********************************************/ 34 void U2G(const char* pUtf8, char* pGb2312); 35  36 /********************************************** 37   *Summary: GB2312转换为UTF-8 38   *Parameters: 39        in pGb2312 传出GB2312字符串 40        out pUtf8 传入UTF-8字符串 41   *Return : no 42 ***********************************************/ 43 void G2U(const char* pGb2312, char* pUtf8); 44  45 /********************************************** 46   *Summary: wstring 转为 string 47   *Parameters: 48        in strWs wstring字符串 49        out no 50   *Return : 转换成功的string字符串 51 ***********************************************/ 52 std::string ws2s(const std::wstring& strWs); 53  54 /********************************************** 55   *Summary: string 转为 wstring 56   *Parameters: 57        in strWs string字符串 58        out no 59   *Return : 转换成功的wstring字符串 60 ***********************************************/ 61 std::wstring s2ws(const std::string& str); 62  63 /********************************************** 64   *Summary: 去掉字符串中的左空格 65   *Parameters: 66        in pStr待处理字符串 67        out pStr处理成功返回的字符串 68   *Return : 转no 69 ***********************************************/ 70 void lTrim(char *pStr); 71  72 /********************************************** 73   *Summary: 去掉字符串中的右空格 74   *Parameters: 75        in pStr待处理字符串 76        out pStr处理成功返回的字符串 77   *Return : 转no 78 ***********************************************/ 79 void rTrim(char *pStr); 80  81 /********************************************** 82   *Summary: 去掉字符串中的左右空格 83   *Parameters: 84        in pStr待处理字符串 85        out no 86   *Return : 处理成功字符串 87 ***********************************************/ 88 std::string Trim(const char* pStr); 89  90 /********************************************** 91   *Summary: 字符串分隔 92   *Parameters: 93        in strSrc 原字符串 94           strSplit 分隔符 95        out vecDest 分隔后的字符串列表 96   *Return : 成功true 错误false 97 ***********************************************/ 98 bool SplitString(const std::string &strSrc,const std::string &strSplit, std::vector<std::string> &vecDest); 99 100 /**********************************************101   *Summary: 将字符串转换成大写102   *Parameters:103        in str 原字符串104        out no105   *Return : no106 ***********************************************/107 void ToUpperString(std::string &str);108 109 /**********************************************110   *Summary: 将字符串转换成小写111   *Parameters:112        in str 原字符串113        out no114   *Return : no115 ***********************************************/116 void ToLowerString(std::string &str);117 118 /**********************************************119   *Summary: base64解码120   *Parameters:121        in str base64字符串122        out no123   *Return : 解码后的字符串124 ***********************************************/125 std::string Base64Decode(const std::string& input);126 127 /**********************************************128   *Summary: 获取一个随机字符串129   *Parameters:130        in iLen 字符串长度 131        out pRndChars 随机字符串132   *Return : no133 ***********************************************/134 void RandChars(char *pRndChars, int iLen);135 136 /**********************************************137   *Summary: 判断IP地址是否合法138   *Parameters:139        in pIp IP地址 140        out no141   *Return : 成功返回0142 ***********************************************/143 int ValidateIpFormat(char *pIp);144 145 /**********************************************146   *Summary: 判断字符串是否为数字147   *Parameters:148        in pIn 输入字符串149        out no150   *Return : 成功返回true151 ***********************************************/152 bool IsNumString(char * pIn);153 154 /**********************************************155   *Summary: 其他类型转换成string156   *Parameters:157        in value 输入值158        out no159   *Return : 转换后字符串160 ***********************************************/161 template<typename T>162 string toString(T value);163 164 /**********************************************165   *Summary: 格式化为字符串166   *Parameters:167        in fmt 输入值168        out no169   *Return : 格式化后字符串170 ***********************************************/171 string format(const char* fmt, ...); 172 173 /**********************************************174   *Summary: 替换字符串中所有的特定字符串(循环替换,比如"12212"中"12″都替换成"21",结果为"22211")175   *Parameters:176        in str 输入字符串177           old_value 需要替换的字符串178           new_value 被替换的字符串179        out no180   *Return : 替换后的字符串181 ***********************************************/182 string& replaceAll(string &str,const string &old_value,const string &new_value);183 184 /**********************************************185   *Summary: 替换字符串中所有的特定字符串(循环替换,比如"12212"中"12″都替换成"21",结果为"21221")186   *Parameters:187        in str 输入字符串188           old_value 需要替换的字符串189           new_value 被替换的字符串190        out no191   *Return : 替换后的字符串192 ***********************************************/193 string& replaceAllDistinct(string &str,const string &old_value,const string &new_value);194 #endif
StrUtils.h

实现文件

  1 #include "StrUtils.h"  2 #include <time.h>  3 #include <stdarg.h>  4 #include <stdio.h>  5 #include <stdlib.h>  6   7 static const char rstr[128] = {  8     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0,  9     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62,    0, 0, 0, 63, 11     52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 12     0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 13     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 14     0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 15     41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0 16 }; 17  18 void U2G(const char* pUtf8, char* pGb2312) 19 { 20     int len = MultiByteToWideChar(CP_UTF8, 0, pUtf8, -1, NULL, 0); 21     wchar_t* wstr = new wchar_t[len+1]; 22     memset(wstr, 0, len+1); 23     MultiByteToWideChar(CP_UTF8, 0, pUtf8, -1, wstr, len); 24     len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL); 25     memset(pGb2312, 0, sizeof(pGb2312)); 26     WideCharToMultiByte(CP_ACP, 0, wstr, -1, pGb2312, len, NULL, NULL); 27     if(wstr) delete[] wstr; 28 } 29  30 void G2U(const char* gb2312, char* utf8) 31 { 32     int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0); 33     wchar_t* wstr = new wchar_t[len+1]; 34     memset(wstr, 0, len+1); 35     MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len); 36     len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); 37     memset(utf8, 0, sizeof(utf8)); 38     WideCharToMultiByte(CP_UTF8, 0, wstr, -1, utf8, len, NULL, NULL); 39     if(wstr) delete[] wstr; 40 } 41  42 std::string ws2s(const std::wstring& strWs) 43 { 44     std::string curLocale = setlocale(LC_ALL, NULL); 45     setlocale(LC_ALL, "chs"); 46     const wchar_t* _Source = strWs.c_str(); 47     size_t _Dsize = 2 * strWs.size() + 1; 48     char *_Dest = new char[_Dsize]; 49     memset(_Dest,0,_Dsize); 50     wcstombs(_Dest,_Source,_Dsize); 51     std::string result = _Dest; 52     delete []_Dest; 53     setlocale(LC_ALL, curLocale.c_str()); 54     return result; 55 } 56  57 std::wstring s2ws(const std::string& str) 58 { 59     setlocale(LC_ALL, "chs");  60     const char* _Source = str.c_str(); 61     size_t _Dsize = str.size() + 1; 62     wchar_t *_Dest = new wchar_t[_Dsize]; 63     wmemset(_Dest, 0, _Dsize); 64     mbstowcs(_Dest,_Source,_Dsize); 65     std::wstring result = _Dest; 66     delete []_Dest; 67     setlocale(LC_ALL, "C"); 68     return result; 69 } 70  71 void lTrim(char *pStr) 72 { 73     char *pTmp = pStr; 74     while(*pTmp ==   || *pTmp == \t){*pTmp++;} 75     strcpy(pStr,pTmp); 76 } 77  78 void rTrim(char *pStr) 79 { 80     int iLen = strlen(pStr)-1; 81     while((pStr[iLen] ==   || pStr[iLen] == \t) && iLen >= 0){iLen--;} 82     pStr[iLen+1] = \0; 83 } 84  85 std::string Trim(const char *pStr) 86 { 87     if (NULL == pStr || 0 == strlen(pStr)) 88     { 89         return std::string(""); 90     } 91  92     int iLen = strlen(pStr) + 1; 93     char* pTmp = (char*)malloc(sizeof(char) * iLen); 94     memset(pTmp, 0, iLen); 95     strncpy(pTmp, pStr, iLen-1); 96     lTrim(pTmp); 97     rTrim(pTmp); 98     std::string strRet = std::string(pTmp); 99     free(pTmp);100     return strRet;101 }102 103 bool SplitString(const std::string &strSrc,104                  const std::string &strSplit,105                  std::vector<std::string> &vecDest)106 {107     if(strSrc.size()==0)108     {   109         return false;110     }   111 112     size_t oldPos,newPos;113     oldPos=0;114     newPos=0;115     std::string tempData;116     while(1)117     {   118         newPos=strSrc.find(strSplit,oldPos);119         if(newPos!=std::string::npos)120         {   121             tempData = http://www.mamicode.com/strSrc.substr(oldPos,newPos-oldPos);122             vecDest.push_back(tempData);123             oldPos=newPos+strSplit.size();124         }   125         else if(oldPos<=strSrc.size())126         {   127             tempData=http://www.mamicode.com/ strSrc.substr(oldPos);128             vecDest.push_back(tempData);129             break;130         }   131         else132         {   133             break;134         }   135     }   136 137     return true;138 }139 140 void ToUpperString(std::string &str)141 {  142     transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);  143 }144 145 void ToLowerString(std::string &str)146 {  147     transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);  148 }149 150 std::string Base64Decode(const std::string& input)151 {152     unsigned int i = 0, l = static_cast<unsigned int>(input.length());153     std::string output;154     output.resize((l / 4 + 1) * 3);155     output = "";156     while (i < l)157     {158         while (i < l && (input[i] == 13 || input[i] == 10))159             i++;160         if (i < l)161         {162             if(i + 3 >= l)return "";163 164             if(input[i] < 0 || input[i + 1] < 0 || input[i + 2] < 0 || input[i + 3] < 0)return "";165             char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) + (rstr[(int)input[i + 1]] >> 4 & 0x03));166             output += b1;167 168             if (input[i + 2] != =)169             {170                 char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + (rstr[(int)input[i + 2]] >> 2 & 0x0f));171                 output += b2;172             }173 174             if (input[i + 3] != =)175             {176                 char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + rstr[(int)input[i + 3]]);177                 output += b3;178             }179             i += 4;180         }181     }182     return output;183 }184 185 void RandChars(char *pRndChars, int iLen)186 {187     char chs[] = {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z};188     int iRnd=0;189     static int iSRnd=0;190     iSRnd++;191     if(iSRnd>100000) iSRnd=0;192     srand((unsigned)time(NULL)+ iSRnd);193     for(int i = 0; i < iLen; i++){194         iRnd = rand() % 36;195         pRndChars[i] = chs[iRnd];196     }197 }198 199 #if _LINUX_200 201 int ValidateIpFormat(char *pIp)202 {203     int iLen = strlen(pIp);204     int iIpV6Flag = 0;205     int iDotCnt = 0;206 207     for (int i=0; i<iLen; i++)208     {209         if ( ! ( (pIp[i]<=9 && pIp[i]>=0) 210             || (pIp[i]==.) 211             || (pIp[i]==:) 212             || (pIp[i]<=f && pIp[i]>=a) 213             || (pIp[i]<=F && pIp[i]>=A) ) )214         {215             return 1;216         }217 218         if (pIp[i]==:)219         {220             iIpV6Flag = 1;221         }222         else if (pIp[i]==.)223         {224             iDotCnt ++;225         }226     }227     if (! iIpV6Flag && iDotCnt != 3)228     {229         return 2;230     }231 232     struct addrinfo hints;233     struct addrinfo *res;234 235     memset(&hints, 0, sizeof(hints));236     hints.ai_family = PF_UNSPEC;237     hints.ai_socktype = SOCK_STREAM;238 239     res = NULL;240     int intRet = getaddrinfo(pIp, NULL, &hints, &res);241     if (res)242     {243         freeaddrinfo(res);244     }245 246     return intRet;247 }248 249 #endif250 251 bool IsNumString(char * pIn)252 {253     int iLen;254     iLen=strlen(pIn);255 256     for(int i=0;i<iLen;i++)257     {258         if(*(pIn+i)<0x30||*(pIn+i)>0x39)259         {260             return false;261         }262     }263     return true;264 }265 266 template<typename T>267 string toString(T value)268 {269     ostringstream ss;270     ss << value;271     return ss.str();272 }273 274 string format(const char* fmt, ...)275 {276     va_list args;277     char* buffer = NULL;278     va_start(args, fmt);279     int rc = vasprintf(&buffer, fmt, args);280     va_end(args);281     string result;282     if (rc >= 0) {283         result = buffer;284     }285     if (buffer != NULL) {286         free(buffer);287     }288     return result;289 }290 291 string& replaceAll(string &str,const string &old_value,const string &new_value)  292 {   293     while(true)   294     {   295         string::size_type pos(0); 296 297         if( (pos = str.find(old_value)) != string::npos ) 298         {299             str.replace(pos,old_value.length(),new_value);   300         }301         else   302         {303             break;   304         }305     }   306 307     return str;   308 }   309 310 string& replaceAllDistinct(string &str,const string &old_value,const string &new_value)   311 {   312     for(string::size_type pos = 0; pos != string::npos; pos += new_value.length())   313     {   314         if( (pos = str.find(old_value,pos)) != string::npos )   315         {316             str.replace(pos,old_value.length(),new_value);   317         }318         else   319         {320             break;   321         }322     }   323 324     return   str;   325 }   
StrUtils.cpp