1、char 与 std::string 之间的转化
使用_sntprintf 与 strcopy实现
char myStr1[20] = "abcdefghijklmn";
std::string myStr2;
_sntprintf((char *)(myStr2.c_str()), sizeof(myStr1), myStr1);
std::string myStr1 = "abcdefghijklmn";
char myStr2[20];
_sntprintf(myStr2, sizeof(myStr2), myStr1.c_str());
以上是使用_sntprintf实现,strcopy也可类似这样使用。
2、strprintf:格式化字符串返回std::string
std::string strprintf(char const * format, ...)
{
char buf[256];
va_list(args);
va_start(args, format);
int nb = _vsnprintf(buf, 256, format, args);
va_end(args);
if(nb<256)
return buf;
++nb;
char *buf2 = new char[nb];
va_start(args, format);
_vsnprintf(buf2, nb, format, args);
va_end(args);
std::string res(buf2);
delete [] buf2;
return res;
}
使用方法:strprintf("图片%d",imageId);
3、tostring:把任意类型值转成std::string
template<typename T> std::string toString(const T &arg)
{
std::stringstream ss;
ss << arg;
return ss.str();
}
4、string 转 UTF8
std::string toUTF8(const std::string &s)
{
USES_CONVERSION;
std::wstring ws = A2W(s.c_str());
vector<char> utf8Str(ws.size()*3 + 1, 0);
WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), ws.size(), &utf8Str[0], utf8Str.size(), NULL, NULL);
return &utf8Str[0];
}
5、ip地址长整数转化为字符串
const char * ipToString(int address)
{
static char asciiIp[16];
sprintf(asciiIp, "%i,%i,%i,%i",
(unsigned char)(address >> 24),
(unsigned char)((address&0x00ffffff) >> 16),
(unsigned char)((address&0x0000ffff) >> 8),
(unsigned char)(address&0x000000ff));
return asciiIp;
}
使用:10.0.3.193转化为整数为167773121
ipToString(167773121) 返回 10.0.3.193
6、分割字符串,保存到容器栈中
bool stringSplit(const std::string& srcStr, const std::string& splitStr, std::vector<std::string>& destVec)
{
if(srcStr.size() == 0)
return false;
size_t oldPos = 0;
size_t newPos = 0;
std::string tempData;
while(true)
{
newPos = srcStr.find(splitStr, oldPos);
if(newPos != std::string::npos)
{
tempData = srcStr.substr(oldPos, newPos - oldPos);
destVec.push_back(tempData);
oldPos = newPos + splitStr.size();
}
else if(oldPos < srcStr.size())
{
tempData = srcStr.substr(oldPos);
destVec.push_back(tempData);
break;
}
else
break;
}
return true;
}
例:字符串“C++,PHP,Java,Python”,调用函数可以把逐个字符串存入容器栈中。
7、去掉字符串中前后的空格字符
std::string &trim(std::string &str)
{
std::string::size_type pos = str.find_last_not_of(' ');
if(pos != std::string::npos)
{
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != std::string::npos)
str.erase(0, pos);
}
else
{
str.clear();
}
return str;
}
8、字符串中字母的大小写转换
std::string &toLower(std::string &str) //转小写
{
std::transform(str.begin, str.end(), str.begin(), tolower);
return str;
}
std::string &toUpper(std::string &str) //转大写
{
std::transform(str.begin, str.end(), str.begin(), toupper);
return str;
}
补充一个字符串处理宏,可以很方便进行字符串的格式化:
#define MAKESTR(s) ((std::ostringstream&)(std::ostringstream()<<std::string()<<s)).str().c_str()
例: std::string mStr = MAKESTR("abcd"<<21<<"love");