1. 程式人生 > >如何判斷兩個字串中是否包含某一符串?

如何判斷兩個字串中是否包含某一符串?

程式碼思路:

        以短字串的長度為單位,進行字串匹配,如果匹配得到的相同字元的個數等於短字串的個數,則判斷長字串包含短字串。

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

bool CompareString(char *firstString, char*secondString);
int main()
{
	bool flag = false;
	char str1[100],str2[100];
	scanf("%s",&str1);
	scanf("%s", &str2);
	printf("str1的長度為:%d str2的長度為:%d\n", strlen(str1),strlen(str2));
	flag = CompareString(str1, str2);
	printf("%d", flag);
	system("pause");
	return 0;
}

bool CompareString(char *firstString, char*secondString)
{
	char *longString, *shortString;
	int j = 0, num = 0;
	bool flag=false;

	if (strlen(firstString) <= strlen(secondString))
	{
		longString = secondString;
		shortString = firstString;
	}
	else
	{
		longString = firstString ;
		shortString = secondString;
	}

	for (int i = 0; i <strlen(longString); i++)
	{
		num = 0;
		for (int j = 0; j < strlen(shortString); j++)
		{
			if (longString[i + num] == shortString[j])
			{
				num++;
				if (num == strlen(shortString))
				{
					flag=true;
				}
			}
			else
			{
				continue;
			}
		}
	}
	return flag;
}