cpp_string

慢慢的把之前收集的代码片段迁移过来。

格式化开源库

fmt

大小写转换

// toUpper
transform(strOutput.begin(), strOutput.end(), strOutput.begin(), ::toupper);
// toLower
transform(strOutput.begin(), strOutput.end(), strOutput.begin(), ::tolower);

sscanf_s

跳过指定字符串

int index = 0;
_stscanf_s(it.c_str(), L"dev_config_%d", &index);

去前后空白字符

#include <vector>
#include <string>
#include <list>
#include <algorithm>
using namespace std;

#ifdef _UNICODE
#define tstring wstring
#else
#define tstring string
#endif // _UNICODE

void strTrim(tstring& s)
{
s.erase(0, s.find_first_not_of(_T(" \t\f\v\n\r")));
s.erase(s.find_last_not_of(_T(" \t\f\v\n\r")) + 1);
}

vector2string

std::vector<char> v;
std::string str(v.begin(), v.end());

排序

string strPlain = w2s(harddriveSN) + w2s(cpuSN) + w2s(originMac);
sort(strPlain.begin(), strPlain.end());

倒序

string strPlain = w2s(harddriveSN) + w2s(cpuSN) + w2s(originMac);
sort(strPlain.begin(), strPlain.end());
reverse(strPlain.begin(), strPlain.end());

base64 编码

https://github.com/ReneNyffenegger/cpp-base64
https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp

拆分字符串

tstring str = _T("1,2,3,45 4,5");
vector<tstring> vBuf;
int iRet = strSplit(str, _T(" ,"), vBuf, 1);

/** split string for stl string type
@param [in] source
@param [in] delimiter
@param [out] out
@param [in] iTrim 1 trim 0 not trim
*/
int strSplit(const tstring& source, const tstring& delimiter, vector<tstring>& out, const int iTrim)
{
out.clear();
TCHAR* pContex;
TCHAR* pFind = _tcstok_s((wchar_t*)source.c_str(), delimiter.c_str(), &pContex);
if (0 == _tcscmp(_T("\0"), pContex))
{
return -1;
}
tstring strTmp;
while (pFind)
{
strTmp = pFind;
if (iTrim)
{
strTrim(strTmp);
}
out.push_back(strTmp);
pFind = _tcstok_s(NULL, delimiter.c_str(), &pContex);
}
return 0;
}


/** split string for stl string type
@param [in] source
@param [in] delimiter
@param [out] out
@param [in] iTrim 1 trim 0 not trim
*/
int stlSplit(const tstring& source, const tstring& delimiter, vector<tstring>& out, int iTrim)
{
size_t fpos = 0, bpos = 0;
out.clear();
tstring strTmp;
while ((fpos = source.find_first_of(delimiter, fpos)) != string::npos)
{
if (iTrim)
{
strTmp = source.substr(bpos, fpos - bpos);
strTrim(strTmp);
if (false == strTmp.empty())
{
out.push_back(strTmp);
}
} else
{
out.push_back(source.substr(bpos, fpos - bpos));
}
++fpos;
bpos = fpos;
}
if (bpos < source.size())
{
if (iTrim)
{
strTmp = source.substr(bpos);
strTrim(strTmp);
if (false == strTmp.empty())
{
out.push_back(strTmp);
}
} else
{
out.push_back(source.substr(bpos));
}
}
return 0;
}
char sentence[] = "192.168...9...14";
cout << "sentence = " << sentence << "\nThe tokens are:\n";
char *p;
char *token = strtok_s(sentence, ".", &p);
while (token != NULL){

cout << token << '\n';
token = strtok_s(NULL, ".", &p);
}

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
char str[] ="This is a sample string,just testing.";
char * pch;
printf ("Splitting string \"%s\" in tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.");
}
return 0;
}

Output:
Splitting string "This is a sample string,just testing." in tokens:
This
is
a
sample
string
just
testing



01.char buf[]="port=5000";
02.char key[100]="";
03.char value[100]="";
04.
05.strcpy(key,strtok(buf,"="));
06.strcpy(value,strtok(NULL,"="));
07.printf("key=%s\n",key);
08.printf("value=%s\n",value);

string to hex byte

/*
Convert string to byte vector
str: [in] string need convert
byte: [in] byte vector for store
return: false is successful, otherwise is true.
*/
bool str2byte(const string& str, vector<unsigned char>& byte)
{
byte.clear();
string str1 = str;
size_t fpos;
while (string::npos != (fpos = str1.find_first_of(" \t\n\r;")))
{
str1.erase(fpos, 1);
}
if (str1.size() % 2)
return true;
int i = 0;
// int dbg = 0;
for (string::const_iterator it = str1.begin(); it != str1.end(); it += 2)
{
if (0 >= sscanf_s((const char*)&(*it), "%02X", &i))
{
return true;
}
//++dbg;
byte.push_back((unsigned char)i);
}
return false;
}

/**
Convert string to byte array
@param str [in] string need convert
@param buf [in] byte array for store
@param len [in][out] array length
@param return
-false is successful
-true is failed
*/
bool str2byte(const string& str, byte* buf, DWORD& len)
{
string str1 = str;
size_t fpos;
while (string::npos != (fpos = str1.find_first_of(" \t\n\r")))
{
str1.erase(fpos, 1);
}
int i = 0;
UINT dbg = 0;
for (string::const_iterator it = str1.begin(); it != str1.end(); it += 2)
{
if (0 >= sscanf_s((const char*)&(*it), "%02X", &i))
{
return true;
}
buf[dbg] = ((unsigned char)i);
++dbg;
if (dbg > len)
{
return true;
}

}
len = dbg;
return false;
}

/*
Convert string to byte vector
str: [in] string need convert
byte: [in] byte vector for store
return: false is successful, otherwise is true.
*/
bool str2byte(const TCHAR* pstr, vector<unsigned char>& vByte)
{
vByte.clear();
wstring str = pstr;
size_t fpos;
while (wstring::npos != (fpos = str.find_first_of(TEXT(" \t\n\r"))))
{
str.erase(fpos, 1);
}
unsigned char uc = 0;
int iTmp = 0;
for (wstring::const_iterator it = str.begin(); it != str.end(); it += 2)
{
if (0 >= _stscanf_s((const TCHAR*)&(*it), TEXT("%02X"), &iTmp))
{
return true;
}
vByte.push_back((unsigned char)iTmp);
}
return false;
}



#ifndef ASLUCKY_STRINGHELPER__
#define ASLUCKY_STRINGHELPER__

/**
convert byte array to tchar vector
@param bArr [in] byte array
@param size [in] byte array size
\param strOut [in] string of data output
\param strOutLen [in] length of strOut buffer
\return
- 0 successful
- 1 string buffer is small
*/
int byte2Str(const BYTE* bArr, const DWORD size, TCHAR* strOut, DWORD strOutLen)
{
strOut[0] = '\0';
if (!size)
{
return 0;
}
DWORD pos = 0;
TCHAR hexval[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
for (DWORD j = 0; j < size; j++)
{
if (pos + 3 > strOutLen)
{
return 1;
}
strOut[pos] = hexval[((bArr[j] >> 4) & 0x0F)];
strOut[pos + 1] = hexval[(bArr[j]) & 0x0F];
strOut[pos + 2] = ' ';
pos += 3;

}
strOut[pos - 1] = '\0';
return 0;
}

/**
convert byte array to tchar vector
@param bArr [in] byte array
@param size [in] byte array size
@param vstr [in] TCHAR vector
*/
void byte2Str(const BYTE* bArr, const DWORD size, vector<TCHAR>& vstr)
{
vstr.clear();
vstr.reserve(500);
if (!size)
{
vstr.push_back('\0');
return;
}
TCHAR hexval[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
for (DWORD j = 0; j < size; j++)
{
vstr.push_back(hexval[((bArr[j] >> 4) & 0x0F)]);
vstr.push_back(hexval[(bArr[j]) & 0x0F]);
vstr.push_back(' ');
}
vstr.push_back('\0');
}

void byte2StrA(const BYTE* bArr, const DWORD size, vector<CHAR>& vstr)
{
vstr.clear();
vstr.reserve(500);
if (!size)
{
vstr.push_back('\0');
return;
}
TCHAR hexval[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
for (DWORD j = 0; j < size; j++)
{
vstr.push_back(hexval[((bArr[j] >> 4) & 0x0F)]);
vstr.push_back(hexval[(bArr[j]) & 0x0F]);
}
vstr.push_back('\0');
}

字符串数字转换

char buf[200] = {'\0'};
if ( -1 == sprintf_s(buf,200,("%04d%02d%02d"),t.wYear,t.wMonth,t.wDay) )
{
logName += "payHelper.txt";
}else
{
logName += &buf[0];
logName += "_xxx.txt";
}

字符串转数字

//C++11
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
long stol (const string& str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);
long double stold (const string& str, size_t* idx = 0);
long double stold (const wstring& str, size_t* idx = 0);
float stof (const string& str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);

int64_t totalSize = _tstoi64(dInfo.totalSize.c_str());
int64_t freeSize = _tstoi64(dInfo.freeSize.c_str());

if (0 == totalSize || 0 == freeSize)
{
dInfo.usedSize = _T("");
}

Parses str interpreting its content as a floating-point number, which is returned as a value of type float.
If idx is not a null pointer, the function also sets the value of idx to the position of the first character in str after the number.

_stscanf_s
sscanf_s

if (1 != _stscanf_s(pstrPort.c_str(), TEXT("%d"), &iPort))
{
return RET_INVALIDE_PARAM;
}


CString thestring("13.37");
double d = atof(thestring).
...or for Unicode builds, _wtof():

CString thestring(L"13.37");
double d = _wtof(thestring).

CString strOrder;
GetDlgItemText(IDC_EDIT_ORDER,strOrder);

double order = _tstof(strOrder);


_tstof atof atof _wtof
_tstoi atoi atoi _wtoi
_tstoi64 _atoi64 _atoi64 _wtoi64
_tstol atol atol _wtol

_tstoi atoi atoi _wtoi
_ttoi atoi atoi _wtoi

_ttoi64 _atoi64 _atoi64 _wtoi64
_ttol atol atol _wtol

数字转字符串

_itoa_s

C++11
#include <string> // std::wstring, std::to_wstring

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

wstring to_wstring (int val);
wstring to_wstring (long val);
wstring to_wstring (long long val);
wstring to_wstring (unsigned val);
wstring to_wstring (unsigned long val);
wstring to_wstring (unsigned long long val);
wstring to_wstring (float val);
wstring to_wstring (double val);
wstring to_wstring (long double val);

宽字符转 ASCII

#include <vector>
#include <string>
#include <list>
#include <algorithm>
using namespace std;

#ifdef _UNICODE
#define tstring wstring
#else
#define tstring string
#endif // _UNICODE

void strTrim(tstring& s)
{
s.erase(0, s.find_first_not_of(_T(" \t\f\v\n\r")));
s.erase(s.find_last_not_of(_T(" \t\f\v\n\r")) + 1);
}

//下面代码在转换mht内容的时候失败了,提示有的字符没有,中文可用
wstring s2w(const string& str)
{
size_t num = 0;
vector<wchar_t>buf(str.size() * 2 + 2);
_locale_t local = _create_locale(LC_ALL, "chs");
//if failed set buf empty string and num = 0
_mbstowcs_s_l(&num, &buf[0], buf.size(), str.c_str(), _TRUNCATE, local);
_free_locale(local);
return &buf[0];
}

string w2s(const wstring& wstr)
{
size_t num = 0;
vector<char>buf(wstr.size() * 2 + 1);
_locale_t local = _create_locale(LC_ALL, "chs");
//if failed set buf empty string and num = 0
_wcstombs_s_l(&num, &buf[0], buf.size(), wstr.c_str(), _TRUNCATE, local);
_free_locale(local);
return &buf[0];
}


//这个目前好用,对中文有问题
std::wstring s2w(const std::string &str)
{
std::wstring wstr(str.length(), L' ');
std::copy(str.begin(), str.end(), wstr.begin());
return wstr;
}

//只拷贝低字节至string中
std::string w2s(const std::wstring &wstr)
{
std::string str(wstr.length(), ' ');
std::copy(wstr.begin(), wstr.end(), str.begin());
return str;
}


//============================================下面代码在转换mht内容的时候失败了,提示有的字符没有 对中文有问题
std::wstring s2w(const std::string &str)
{
wstring wstr;
size_t nLen = str.size();
wstr.resize(nLen, L' ');
int nResult = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str.c_str(), nLen, (LPWSTR)wstr.c_str(), nLen);
if (nResult == 0)
{
wstr = _T("");
}
return wstr;
}

//wstring高字节不为0,返回FALSE
std::string w2s(const std::wstring &wstr)
{
string str;
size_t nLen = wstr.size();
str.resize(nLen, ' ');
int nResult = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wstr.c_str(), nLen, (LPSTR)str.c_str(), nLen, NULL, NULL);
if (nResult == 0)
{
str = "";
}
return str;
}