Skip to content

Instantly share code, notes, and snippets.

@Battleroid
Last active December 14, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Battleroid/5090641 to your computer and use it in GitHub Desktop.
Save Battleroid/5090641 to your computer and use it in GitHub Desktop.
Find common prefix among two strings.
#include <iostream>
#include <cmath>
using namespace std;
template<typename T>
T getDiff(const T a, const T b) {
if (a >= b)
return a;
else if (b > a)
return b;
}
string getPrefix(const string a, const string b) {
string prefix;
for (int i = 0; i < getDiff(a.length(), b.length()); i++) {
if (a[i] == b[i]) {
prefix += a[i];
}
}
return prefix;
}
int main () {
string one = "Test";
string two = "Tesj";
cout << "a: Test, b: Tesj" << endl;
cout << "longest portion: " << getDiff(one.length(), two.length()) << endl;
cout << "prefix: " << getPrefix(one, two) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment