1. 程式人生 > >C語言版字串查詢函式,字串中查詢子串

C語言版字串查詢函式,字串中查詢子串

作業系統: Windows10 64位

執行環境: Visual Studio 10

依賴的標頭檔案:

#include <string.h>
#include <stdlib.h>


/***************************************************************
/*	函 數 名:FindSubstring
/*	函式功能:C語言版,在字串中查詢子串
/*	參    數:
/*			  strSource:待查詢的源字串
/*			  strSub:	 要查詢的子串
/*	返 回 值:
/*			  返回 0,表示查詢成功
/*			  返回-1,表示查詢失敗
/*
/*	作    者:X攻城獅
/*	日    期:2015年11月4日
/***************************************************************/
int FindSubstring (const char *strSource, const char *strSub)
{
	unsigned int uLen = strlen(strSource);
	if (uLen == 0)
	{
		return -1;
	}
	char *str1 = (char *)malloc(uLen+1);
	memset(str1, 0, uLen+1);
	strcpy(str1, strSource);

	uLen = strlen(strSub);
	if (uLen == 0)
	{
		free(str1);
		return -1;
	}
	char *str2 = (char *)malloc(uLen+1);
	memset(str2, 0, uLen+1);
	strcpy(str2, strSub);

	unsigned int i = 0, j = 0;
	for(i=0; i<=strlen(strSource); i++)
	{
		if (str1[i] == str2[j])
		{
			j++;
		}
		else
		{
			if (j == uLen)
			{
				break;
			}
			else
			{
				j = 0;
			}
		}
	}

	free(str1);
	free(str2);

	if (j == uLen)
	{
		return 0;
	} 
	else
	{
		return -1;
	}
}