c# 字符串比较方法返回第一个不匹配的索引

标签 c# string-matching

是否有一种现有的字符串比较方法会根据两个字符串之间首次出现的不匹配字符返回一个值?

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/

相关文章:

c# - using(object obj = new Object()) 是什么意思?

c# - 在 ThreadAbortException 上下文中防止资源泄漏的推荐方法是什么?

c# - 缓存页面的仅限管理员内容

javascript - JS 中的正则表达式 - 匹配整个单词,除了末尾的可选 s

ruby - 模糊文档匹配/文本指纹识别的最佳库

c# - 在数据网格中绑定(bind)枚举属性的最佳方法

regex - 需要使用 RegEx 防止重复字符

sql - 模糊逻辑匹配

algorithm - 一次搜索多个模式的最佳字符串匹配算法是什么?

c# - 关于使用 Monitor.TryEnter 和锁定对象的问题