1. 程式人生 > >c實現的字串查詢函式

c實現的字串查詢函式

1. c++貌似有這樣的方法,我用c程式碼實現了一遍,沒有實現演算法優化。可以解決基本的字串查詢需求。

/*** 返回 buf找到的與expr完全匹配的第一項的第一個字元的索引
   * zgr 2013-05-23
   * buf-源字串
   * offset-源字串偏移-從偏移量往後搜尋
   * expr-匹配字串
   * bufMaxLen-源字串長度
   */
int findFirst(const char* buf, int offset, const char* expr, int bufMaxLen)
{
	if(buf == NULL || offset<0 || offset>bufMaxLen-1)
	{
		return -1;
	}
	const char* p1;
	const char* p2;
	p1 = buf+offset;
	p2 = expr;
	int curoffset = offset;
	int sameTimes = 0;
	int exprOffSet = -1;
	while(curoffset<bufMaxLen)
	{
		if(*p1==*p2 && sameTimes==0)
		{
			exprOffSet = curoffset;
			p1++;
			p2++;
			curoffset++;
			sameTimes++;
		}
		else if(*p1==*p2 && sameTimes<strlen(expr))
		{
			p1++;
			p2++;
			curoffset++;
			sameTimes++;
			if(sameTimes==strlen(expr))
			{
				return exprOffSet;
			}
		}
		else
		{
			if(exprOffSet>=0)
			{
				p1 = buf+exprOffSet+1;
				p2 = expr;
				curoffset = exprOffSet+1;
				sameTimes = 0;
				exprOffSet = -1;
			}
			else
			{
				p1++;
				curoffset++;
			}
		}
	}
	return -1;
}
這個是從後往前查詢
/*** 返回 buf找到的與expr完全匹配的最後一項的第一個字元的索引
   * zgr 2013-05-23
   * buf-源字串
   * expr-匹配字串
   * bufMaxLen-源字串長度
   */
int findLast(const char* buf, const char* expr, int bufMaxLen)
{
	if(buf==NULL || bufMaxLen<0 || expr==NULL)
	{
		return -1;
	}
	const char* p1;
	const char* p2;
	p1 = buf+bufMaxLen-1;
	p2 = expr+strlen(expr)-1;
	int curoffset = bufMaxLen-1;
	int sameTimes = 0;
	int exprOffSet = -1;
	while(curoffset>=0)
	{
		if(*p1==*p2 && sameTimes==0)
		{
			exprOffSet = curoffset;
			p1--;
			p2--;
			curoffset--;
			sameTimes++;
		}
		else if(*p1==*p2 && sameTimes<strlen(expr))
		{
			sameTimes++;
			if(sameTimes==strlen(expr))
			{
				return exprOffSet-(strlen(expr)-1);
			}
			p1--;
			p2--;
			curoffset--;
		}
		else
		{
			if(exprOffSet>=0)
			{
				p1 = buf+(exprOffSet-1);
				p2 = expr+strlen(expr)-1;
				curoffset = exprOffSet-1;
				sameTimes = 0;
				exprOffSet = -1;
			}
			else
			{
				p1--;
				curoffset--;
			}
		}
	}
	return -1;
}