在使用.net时候,发现字符串非常好用,分析字符串的时候非常方便!但是stl的string就不一样了,所以在网上整理人家写的一些辅助函数,这里没有考虑性能,只是考虑怎么使用起来方便
#pragma once
#include <string>
#include <vector>
#include <algorithm>
class StringHelper
{
public:
StringHelper(void);
~StringHelper(void);
static std::string& trim(std::string& str)
{
if (str.empty())
{
return str;
}
str.erase(0,str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return str;
}
static std::vector<std::string> split(std::string& s, std::string& delim)
{
std::vector< std::string > ret;
size_t last = 0;
size_t index=s.find_first_of(delim,last);
while (index!=std::string::npos)
{
ret.push_back(s.substr(last,index-last));
last=index+1;
index=s.find_first_of(delim,last);
}
if (index-last>0)
{
ret.push_back(s.substr(last,index-last));
}
return ret;
}
static std::string replace(const std::string& str, const std::string& src, const std::string& dest)
{
std::string ret;
std::string::size_type pos_begin = 0;
std::string::size_type pos = str.find(src);
while (pos != std::string::npos)
{
ret.append(str.data() + pos_begin, pos - pos_begin);
ret += dest;
pos_begin = pos + src.length();
pos = str.find(src, pos_begin);
}
if (pos_begin < str.length())
{
ret.append(str.begin() + pos_begin, str.end());
}
return ret;
}
static std::string tolower(const std::string str)
{
std::string data = str;
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
return data;
}
static std::string toupper(const std::string str)
{
std::string data = str;
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
return data;
}
};
测试代码:
int _tmain(int argc, _TCHAR* argv[])
{
std::string strTrim = " hello world ";
printf( StringHelper::trim(strTrim).c_str() );printf("\n");
std::string strSplit = "F:\\GreenSoft\\Adobe Photoshop CS5 Extended\\Photoshop\\Presets\\Actions";
std::vector<std::string> strSet = StringHelper::split(strSplit, std::string("\\"));
for ( int i = 0; i < strSet.size(); i ++ )
{
printf("%d %s\n", i, strSet[i].c_str());
}
std::string strReplace = StringHelper::replace(strSplit, "Photoshop", "ps");
printf("%s\n", strReplace.c_str());
std::string strUpperLowerCase = "Hello World!";
std::string low = StringHelper::tolower(strUpperLowerCase);
printf("%s\n", low.c_str());
std::string up = StringHelper::toupper(strUpperLowerCase);
printf("%s \n", up.c_str());
getchar();
return 0;
}