VC++ 库中, 似乎并没有特别好的 SPLIT 字符串拆分函数. 现在自己定义一个吧.
编译环境: VS 2012, UNICODE
#include <vector> using namespace std; vector<CString> split(CString &str, const CString find, int limit = 0) //这后面的 limit 可以指定拆分字符串的次数哦. { vector<CString> ret; int start = 0; int pos = str.Find(find, start); int len = find.GetLength(); int i = 0; while (true) { if (pos < 0 || (limit > 0 && i + 1 == limit)) { //NO FIND ret.push_back(str.Mid(start)); break; } else { ret.push_back(str.Mid(start, pos - start)); start = pos + len; pos = str.Find(find, start); } i++; } return ret; }
应用示例:
----------------------------
CString t = L"a,.b,.c,de.f"; vector<CString> tData = split(t, L"."); //这里的分隔符是支持多个字符串的哦. CString out = L""; for (vector<CString>::iterator iter = tData.begin(); iter != tData.end(); ++iter) { //this->MessageBox(*iter); out += *iter; out += L"\r\n"; out += L"-----------------"; out += L"\r\n"; } this->MessageBox(out);