1. 程式人生 > >取兩個相似字符串的不同部分

取兩個相似字符串的不同部分

bstr Go length end body == between diff str

void DiffBetweenString(string str1, string str2, int& nDiffFirst, int& nDiffLength)
{
int nLength = str1.length() - str2.length();
string longString;
string shortString;
if (nLength > 0)
{
longString = str1;
shortString = str2;
}
else
{
nLength = -nLength;
longString = str2;
shortString = str1;
}

nDiffFirst = 0;
nDiffLength = nLength;
int nDiffEnd = longString.length() > 0 ? longString.length() - 1 : 0;
if (shortString.length() == 0 || longString.length() == 0)
goto Exit;

while (nDiffFirst < shortString.length() && longString[nDiffFirst] == shortString[nDiffFirst])
++nDiffFirst;
if (nDiffFirst == shortString.length())
goto Exit;

while (nDiffEnd - nLength > 0 && longString[nDiffEnd] == shortString[nDiffEnd - nLength])
--nDiffEnd;

nDiffLength = nDiffEnd - nDiffFirst;
if (nDiffLength < 0)
{
nDiffLength = (-nDiffLength) > nLength ? nLength : (-nDiffLength);
}
else
{
++nDiffLength;
}

Exit:

cout << longString.substr(nDiffFirst, nDiffLength) << endl;
cout << shortString.substr(nDiffFirst, nDiffLength - nLength) << endl;
}

取兩個相似字符串的不同部分