stl string 使用
1. 查找字符
std::wstring strData = L"<result>[北京市, 上海市, 深圳市]</result>"
void DoF(const std::wstring &strData, std::list<std::wstring>& listDo)
{
std::wstring strTarB = L"<result>[";
std::wstring strTarE = L"]</result>";
std::wstring::size_type nBeginTempB = 0, nEndTempB = 0, nBeginTempE = 0, nEndTempE = 0;
nEndTempB = strData.find(strTarB, nBeginTempB);
nEndTempE = strData.find(strTarE, nBeginTempE);
if(nEndTempB != std::wstring::npos && nEndTempE != std::wstring::npos && nEndTempE > nEndTempB + strTarB.length())
{
std::wstring strTemp = strData.substr(nEndTempB + strTarB.length(), nEndTempE - nEndTempB - strTarB.length());
std::wstring strSub;
strTemp += L",";
std::list<std::wstring>::iterator it;
listDo.clear();
std::wstring::size_type nBegin = 0, nEnd = 0;
while( (nEnd = strTemp.find(L",", nBegin)) != std::wstring::npos)
{
strSub = strTemp.substr(nBegin, nEnd - nBegin);
if(strSub.length() > 0)
{
listDo.push_back(strSub);
}
nBegin = nEnd + 1;
}
}
}
2. 替换字符串
stl 中的string只是提供了按照位置和区间的replace函数,而不能用一个string字串来替换指定string中的另一个字串.
void string_replace(std::string& strBig, const std::string & strsrc, const std::string &strdst)
{
std::string::size_type pos = 0;
while( (pos = strBig.find(strsrc, pos)) != string::npos)
{
strBig.replace(pos, strsrc.length(), strdst);
pos += strdst.length();
}
}
// 使用
std::string strinfo= "This is Winter, Winter is a programmer. Do you know Winter?";
// 把strinfo中的所有"Winter" 替换为"wende"
string_replace(strinfo, "Winter", "wende");