How to check if two equal-length strings are at least 50% equal in C++

1 Answer

0 votes
#include <string>
#include <iostream>

bool are50PercentEqual(const std::wstring &str1, const std::wstring &str2) {
	if (str1 == L"" || str2 == L"" || str1.length() != str2.length()) {
		return false;
	}

	int matchingChars = 0;

	for (int i = 0; i < str1.length(); i++) {
		if (str1[i] == str2[i]) {
			matchingChars++;
		}
	}

	return static_cast<double>(matchingChars) / str1.length() >= 0.5;
}

int main()
{
	std::wstring str1 = L"java c# c++ php python";
	std::wstring str2 = L"java c# c++ r rust sql";

	if (are50PercentEqual(str1, str2)) {
		std::wcout << L"yes" << std::endl;
	}
	else {
		std::wcout << L"no" << std::endl;
	}
}

 
 
   
/*
run:

yes
  
*/

 



answered May 10, 2024 by avibootz

Related questions

1 answer 103 views
...