C++判斷字符串a內是否含有字符串b

還是一樣。工作的時候用到了這個。下面給一個封裝使用。
也是在網上找的。
c++

#include <iostream>
using namespace std;
int is_begin_with(const char * str1, char *str2)
{
	if (str1 == NULL || str2 == NULL)
		return -1;
	int len1 = strlen(str1);
	int len2 = strlen(str2);
	if ((len1 < len2) || (len1 == 0 || len2 == 0))
		return -1;
	char *p = str2;
	int i = 0;
	while (*p != '\0')
	{
		if (*p != str1[i])
			return 0;
		p++;
		i++;
	}
	return 1;
}
int main()
{
	//方法一
	char a[100] = { "1234" };
	char b[8] = { "12" };

	if (is_begin_with(a, b) == 1)
	{
		cout << "有" << endl;
	}
	else
	{
		cout << "沒有" << endl;
	}
	//方法二
	string::size_type idx;
	string aa = "1234";
	string bb = "12";
	idx = aa.find(bb);//在aa中查找bb.
	if (idx == string::npos)//不存在。
	{
		cout << "沒有" << endl;
	}
	else//存在。
	{
	cout << "有" << endl;
	}


	getchar();
	return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章