是否有一种现有的字符串比较方法会根据两个字符串之间首次出现的不匹配字符返回一个值?
即
string A = "1234567890"
string B = "1234567880"
我想取回一个值,使我能够看到匹配中断的第一次出现是 A[8]
最佳答案
/// <summary>
/// Gets a first different char occurence index
/// </summary>
/// <param name="a">First string</param>
/// <param name="b">Second string</param>
/// <param name="handleLengthDifference">
/// If true will return index of first occurence even strings are of different length
/// and same-length parts are equals otherwise -1
/// </param>
/// <returns>
/// Returns first difference index or -1 if no difference is found
/// </returns>
public int GetFirstBreakIndex(string a, string b, bool handleLengthDifference)
{
int equalsReturnCode = -1;
if (String.IsNullOrEmpty(a) || String.IsNullOrEmpty(b))
{
return handleLengthDifference ? 0 : equalsReturnCode;
}
string longest = b.Length > a.Length ? b : a;
string shorten = b.Length > a.Length ? a : b;
for (int i = 0; i < shorten.Length; i++)
{
if (shorten[i] != longest[i])
{
return i;
}
}
// Handles cases when length is different (a="1234", b="123")
// index=3 would be returned for this case
// If you do not need such behaviour - just remove this
if (handleLengthDifference && a.Length != b.Length)
{
return shorten.Length;
}
return equalsReturnCode;
}
关于c# 字符串比较方法返回第一个不匹配的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504266/