Question:
There are not many such questions. But all I've found are looking for either specific chunks in strings or just matching characters. The question is. There is List filled with lines. In this sheet, you need to find the part common to all lines. BUT! You need to find not all matching characters, but the first matching part. For instance:
QWERTY12345 YU
QWER TY4564 F
QWERGH145
QWER T777
QWE RBT
The result of such a comparison should be QWE.
Tried something like this.
public static string CommonString(string first, string second)
{
return new string((first.Intersect(second)).ToArray());
}
But she seems to be looking for exactly all the characters encountered and does an aggregate, which means she doesn’t fit.
Answer:
Just compare all the first characters, then all the second ones, and so on. until you meet at least one that does not match …
I can sketch in C/C++, C# is not mine…
In C++, something like
string common(const vector<string>& sts)
{
for(int i = 0;;++i)
for(int j = 1; j < sts.size(); ++j)
if (sts[j-1][i] != sts[j][i])
return sts[0].substr(0,i);
}
Update Taking into account the comments made in the comments:
string common(const vector<string>& sts)
{
if (sts.size() == 0) return "";
if (sts.size() == 1) return sts[0];
for(int i = 0;;++i)
{
for(int j = 1; j < sts.size(); ++j)
if (sts[j-1][i] != sts[j][i])
return sts[0].substr(0,i);
if (sts[0][i] == 0) return sts[0];
}
}