C++字符分割

AfxExtractSubString

表头: <afxwin.h>

BOOL AFXAPI AfxExtractSubString ( CString& rString, LPCTSTR lpszFullString, int iSubString, TCHAR chSep = ' ');

参数

rString 对CString将得到一个单独的子字符串的对象。

lpszFullString 字符串包含字符串的全文提取自。

iSubString 提取的子字符串的从零开始的索引从lpszFullString。

chSep 使用的分隔符分隔子字符串,默认的是' '。

返回值

TRUE ,如果函数成功提取了该子字符串中提供的索引;否则, FALSE。

例:

// 使用AfxExtractSubString分割字符串
void CSplitString::SplitString1()
{
    std::vector<long> arrPic;

    CString strContent = _T("1,2,3,4,5");
    CString strTemp;
    int iPos = 0;

    while (AfxExtractSubString(strTemp, strContent, iPos, ','))
    {
        iPos++;
        arrPic.push_back(_wtol(strTemp));
    }
}

STL find_first_of

// 利用STL自己实现字符串分割
void CSplitString::SplitString2()
{
	const std::string s("1,2,3,4,5;6;7;8;9");
	std::vector<std::string> v;
	const std::string c(",;");//多个分隔符

	std::string::size_type pos1, pos2;
	pos2 = s.find_first_of(c);
	pos1 = 0;
	while (std::string::npos != pos2)
	{
		v.push_back(s.substr(pos1, pos2 - pos1));

		pos1 = pos2 + 1;
		pos2 = s.find_first_of(c, pos1);
	}
	if (pos1 != s.length())
		v.push_back(s.substr(pos1));
}

_tcstok_s

// 使用C的_tcstok分割字符串
void CSplitString::SplitString3()
{
	CString str = _T("a,b*c,d");
	TCHAR seps[] = _T(",*");//可按多个字符来分割
	TCHAR *next_token1 = NULL;
	TCHAR* token = _tcstok_s((LPTSTR)(LPCTSTR)str, seps,&next_token1);
	while (token != NULL)
	{
		TRACE("
str=%s  token=%s
", str, token);
		token = _tcstok_s(NULL, seps, &next_token1);
	}
}

http://www.qiezichaodan.com/mfc_cstring_split/

http://blog.csdn.net/xjw532881071/article/details/49154911

http://www.cnblogs.com/happykoukou/p/5427268.html

参考:

原文地址:https://www.cnblogs.com/yhcao/p/6237615.html