一個微軟沒有公佈的提取,分割字串的函式-超級好用

youhello發表於2007-09-12

不錯,方便實用!

c庫的strtok函式也不錯。

[@more@]

123 456 789 012 345

大家經常要用到把上面的這個字串按照空格分割.

以前也是自己寫分割函式.

今天,無意看到微軟其實自帶這個函式的,不過沒有公佈而已.

這個函式就是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部落格 ” ,連結:http://blog.itpub.net/79126/viewspace-969096/,如需轉載,請註明出處,否則將追究法律責任。

相關文章