赞助

stl string 使用(转载)

出处:http://www.cnblogs.com/lzjsky/archive/2011/01/23/1942508.html

1. 查找字符

 1 std::wstring  strData = L"<result>[北京市, 上海市, 深圳市]</result>"
 2 
 3 void DoF(const std::wstring &strData, std::list<std::wstring>& listDo)
 4 
 5 {
 6 
 7     std::wstring strTarB = L"<result>[";
 8 
 9     std::wstring strTarE = L"]</result>";
10 
11  
12 
13     std::wstring::size_type nBeginTempB = 0, nEndTempB = 0, nBeginTempE = 0, nEndTempE = 0;
14 
15    
16 
17     nEndTempB = strData.find(strTarB, nBeginTempB);
18 
19     nEndTempE = strData.find(strTarE, nBeginTempE);
20 
21  
22 
23     if(nEndTempB != std::wstring::npos && nEndTempE != std::wstring::npos && nEndTempE > nEndTempB + strTarB.length())
24 
25     {
26 
27         std::wstring strTemp = strData.substr(nEndTempB + strTarB.length(), nEndTempE -  nEndTempB - strTarB.length());
28 
29         std::wstring strSub;
30 
31         strTemp += L",";
32 
33  
34 
35         std::list<std::wstring>::iterator it;
36 
37         listDo.clear();
38 
39         std::wstring::size_type nBegin = 0, nEnd = 0;
40 
41         while( (nEnd = strTemp.find(L",", nBegin)) != std::wstring::npos)
42 
43         {
44 
45             strSub = strTemp.substr(nBegin, nEnd - nBegin);
46 
47             if(strSub.length() > 0)
48 
49             {
50 
51                 listDo.push_back(strSub);
52 
53             }
54 
55             nBegin = nEnd + 1;
56 
57         }
58 
59     }
60 
61 }

2. 替换字符串

stl 中的string只是提供了按照位置和区间的replace函数,而不能用一个string字串来替换指定string中的另一个字串.

 1 void string_replace(std::string& strBig, const std::string & strsrc, const std::string &strdst)
 2 
 3 {
 4 
 5      std::string::size_type pos = 0;
 6 
 7      while( (pos = strBig.find(strsrc, pos)) != string::npos)
 8 
 9      {
10 
11          strBig.replace(pos, strsrc.length(), strdst);
12 
13          pos += strdst.length();
14 
15      }
16 
17 }
18 
19 // 使用
20 
21 std::string strinfo= "This is Winter, Winter is a programmer. Do you know Winter?";
22 
23 // 把strinfo中的所有"Winter" 替换为"wende"
24 
25 string_replace(strinfo, "Winter", "wende");

 

posted @ 2014-08-05 10:12  车臣  阅读(278)  评论(0编辑  收藏  举报