|
前言:我本人一直很不待见C++,但公司里的工程都是C++写的,不爽归不爽,还是被迫使用了一段时间。最近发现C++比起C来,某些地方还是有点优势的,比如字符串处理。C++里字符串类型很多,除了经典的CHAR*和WCHAR*,还有CString和std::string。个人不推荐用CString,因为这货是微软一家的,而std::string则是多平台兼容的。
一、使用std::string需要包含什么?
二、如何利用std::string和std::vector实现类似VB6的Split函数(根据标识符把字符串分割为多个子字符串)?
- #include <string>
- #include <vector>
- void SplitStdString(const std::string& s, std::vector<std::string>& v, const std::string& c)
- {
- std::string::size_type pos1, pos2;
- pos2 = s.find(c);
- pos1 = 0;
- while(std::string::npos != pos2)
- {
- v.push_back(s.substr(pos1, pos2-pos1));
- pos1 = pos2 + c.size();
- pos2 = s.find(c, pos1);
- }
- if(pos1 != s.length())
- v.push_back(s.substr(pos1));
- }
- int main()
- {
- char g_fw_policy1[]="4444;333;22;1";
- char g_fw_policy2[]="a||bb||ccc||dddd";
- std::vector<std::string> v;
- std::string s;
- //
- s = g_fw_policy1;
- SplitStdString(s,v,";");
- for(long i=0;i<v.size();i++)
- puts(v.at(i).c_str());
- //
- v.clear();
- s = g_fw_policy2;
- SplitStdString(s,v,"||");
- for(long i=0;i<v.size();i++)
- puts(v.at(i).c_str());
- system("pause");
- return 0;
- }
复制代码
三、如何把std::string转为CString
四、如何把std::string里所有的A字符串都替换为B字符串?
- void ReplaceStdString(std::string &String, const std::string &strsrc, const std::string &strdst)
- {
- std::string::size_type pos = 0;
- std::string::size_type srclen = strsrc.size();
- std::string::size_type dstlen = strdst.size();
- while( (pos=String.find(strsrc, pos)) != std::string::npos )
- {
- String.replace( pos, srclen, strdst );
- pos += dstlen;
- }
- }
复制代码 |
评分
-
查看全部评分
|