<pre name="code" class="cpp">
/*
* 功能:提炼字符串;按第二个参数为分隔符解析字符串,返回由
* 参数nWhichOne 指定下标(由1开始计算)处的字符地址,其
* 长度保存在参数pLength 中。
* 参数:
* const char *szSourcString, 要解析的字符串;
* char chSeparator, 指定分隔符;
* int nWhichOne, 指定要得到解析出来的第几个字符串;
* int *pLength, 带回解析成功后返回字符串的长度。
* 返回值:
* const char *, 返回一个找到的字符地址;如果失败,返回NULL。
* 该返回值不以尾零为结束标志,以pLength 为标准。即:两
* 个参数一起确定所得到的字符串。
*
* 例子:
* const char *szParam = "MsgType|Buffer|Process|NMLFile";
* int nLengthMsgType = 0;
* int nLengthBuffer = 0;
* int nLengthProcess = 0;
* int nLengthNMLFile = 0;
* const char *pMsgType = ExtractString(szParam, '|', 1, &nLengthMsgType);
* const char *pBuffer = ExtractString(szParam, '|', 2, &nLengthBuffer );
* const char *pProcess = ExtractString(szParam, '|', 3, &nLengthProcess);
* const char *pNMLFile = ExtractString(szParam, '|', 4, &nLengthNMLFile);
*
* // 结果
* pMsgType = "MsgType|Buffer|Process|NMLFile";
* nLengthMsgType = 7; // "MsgType"
*
* pBuffer = "Buffer|Process|NMLFile";
* nLengthBuffer = 6; // "Buffer"
*
* pProcess = "Process|NMLFile";
* nLengthProcess = 7; // "Process"
*
* pNMLFile = "NMLFile";
* nLengthNMLFile = 7; // "NMLFile"
*/
const char * ExtractString(
const char *szSourcString, char chSeparator,
int nWhichOne, int *pLength)
{
if (szSourcString == NULL || pLength == NULL)
return NULL;
const char *pStringStart = NULL; // 提炼到的字符串的首字符地址
const char *pStringEnd = NULL; // 提炼到的字符串的尾字符的下一个地址
int nPrevIndex = 0; // 首字符在szSourceString 的下标位置
int nEndIndex = 0; // 尾字符的下一个字符在szSourceString 的下标位置
int nCountSepa = 0; // 第nCountSepa 个分隔符
for (int i = 0; i < (int)strlen(szSourcString); ++i)
{
if (szSourcString[i] == chSeparator)
{
if (++nCountSepa == nWhichOne)
{
nEndIndex = i;
break;
}
nPrevIndex = i + 1;
}
}
// 要提炼字符串的位置超出实际拥有的字符串
if (nWhichOne > nCountSepa + 1)
return NULL;
pStringStart = szSourcString + nPrevIndex;
pStringEnd =
(nEndIndex > 0)
? szSourcString + nEndIndex
: szSourcString + strlen(szSourcString);
*pLength = pStringEnd - pStringStart;
return pStringStart;
}