首页 > IT职业 > IT生活 > 一个微软没有公布的提取,分割字符串的函数-超级好用
不错,方便实用!
c库的strtok函数也不错。
[@more@]大家经常要用到把上面的这个字符串按照空格分割.
以前也是自己写分割函数.
今天,无意看到微软其实自带这个函数的,不过没有公布而已.
这个函数就是AfxExtractSubString, 其所在头文件AFXWIN.H
函数原型
BOOL AFXAPI AfxExtractSubString(CString& rString, LPCTSTR lpszFullString,
int iSubString, TCHAR chSep = ' ');
举个例子:
CString strTestBuf = "123456789,12345678,123456789,";
CString strTempsave;
AfxExtractSubString(strTempsave,strTestBuf, 0, ',');
详细的例子如下:
// Open the text file we want
CFile cfFile ("C:TextFile.txt", CFile::modeNoTruncate | CFile::modeRead);
CArchive ar (&cfFile, CArchive::load); // Load its contents into a CArchive
// Initialise the variable which holds each line's contents
CString strLine = "";
if(!ar.ReadString(strLine))
// Read the first line of the CArchive into the variable
return; // Failed, so quit out
do // Repeat while there are lines in the file left to process
{
if(strLine.GetLength() == 0) // If the line is empty, skip it
continue;
CString strText = strLine; // A line of the file
// Initialise the variables that will hold the values
CString strItemName = "";
CString strPicPath = "";
CString strSoundPath = "";
// Extract the first value, and place it in the strItemName variable
AfxExtractSubString(strItemName, strText, 0, ',');
// Extract the second value, and place it in the strPicPath variable
AfxExtractSubString(strPicPath, strText, 1, ',');
// Extract the third value, and place it in the strSoundPath variable
AfxExtractSubString(strSoundPath, strText, 2, ',');
// Do something with these values in the variables
}while(ar.ReadString(strLine));
字符串中去除空格可以采用strTmp.Replace(" ","")方法即可!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/79126/viewspace-969096/ ,如需转载,请注明出处,否则将追究法律责任。