提炼字符串

<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;
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值