两个字符串的最长公共单词

用strtok拆分字符串,strcmp比较字符串是否相等,strlen比较相等字符串的大小

char*strtok(char*strTOKen,const char*strDelimit);

第一个参数:字符串

第二个参数:字符串的分隔符

/*输出两个字符串的最长公共单词*/
void Lostcommonwoed(char*str,char*arr)
{
	int Max = 0;
	vector<char*> q;
	vector<char*> s;
	const char sep[] = " .,";//分隔符
	char* tok = nullptr;
	char* fdr = nullptr;
	int len = 0;//存储最大长度
	char* r = nullptr;//指向最长公共单词
	for (tok = strtok(str, sep); tok != nullptr; tok = strtok(nullptr, sep))
	{
		q.push_back(tok);
	}
	for (fdr = strtok(arr, sep); fdr != nullptr; fdr = strtok(nullptr, sep))
	{
		s.push_back(fdr);
	}
	for (int i = 0; i < q.size(); i++)
	{
		for (int j = 0; j < s.size(); j++)
		{
			if (strcmp(q[i], s[j]) == 0)
			{
				int n = strlen(q[i]);
				if (n > len)
				{
					len = n;
					r = q[i];
				}
			}
		}
	}
	cout << len << endl;
	cout << r << endl;
}
void main()
{
	char str[] = "i.am,a student";
	char arr[] = "you are a student";
	Lostcommonwoed(str, arr);
}

运行结果:

猜你喜欢

转载自blog.csdn.net/qq_70799748/article/details/129997249
今日推荐