And*_*ndy 18 c# string-matching
是否有一个exsting字符串比较方法,它将根据两个字符串之间非匹配字符的第一次出现返回一个值?
即
string A = "1234567890"
string B = "1234567880"
Run Code Online (Sandbox Code Playgroud)
我想得到一个值,这将使我看到匹配中断的第一次出现是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;
}
Run Code Online (Sandbox Code Playgroud)
如果您安装了 .net 4.0,这可能是一种方法:
string A = "1234567890";
string B = "1234567880";
char? firstocurrence = A.Zip(B, (p, q) => new { A = p, B = q })
.Where(p => p.A != p.B)
.Select(p => p.A)
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
编辑:
不过,如果您需要这个职位:
int? firstocurrence = A.Zip(B, (p, q) => new { A = p, B = q })
.Select((p, i) => new { A = p.A, B = p.B, idx = i })
.Where(p => p.A != p.B)
.Select(p => p.idx)
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)