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

本文关键字:不匹配 索引 第一个 返回 字符串 比较 方法 | 更新日期: 2023-09-27 18:17:44

是否有一个现有的字符串比较方法,将根据两个字符串之间的非匹配字符的第一次出现返回一个值?

string A = "1234567890"
string B = "1234567880"

我想要得到一个值,它将允许我看到第一次出现匹配断行是a [8]

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

/// <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;
}

如果你安装了。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();
编辑:

但是,如果你需要这个职位:

    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();

下面的扩展方法可以完成这项工作:

public static int Your_Name_Here(this string s, string other) 
{
    string first = s.Length < other.Length ? s : other;
    string second = s.Length > other.Length ? s : other;
    for (int counter = 0; counter < first.Length; counter++)
    {
        if (first[counter] != second[counter])
        {
            return counter;
        }
    }
    return -1;
}

我不知道,但这是相当微不足道的:

public static int FirstUnmatchedIndex(this string x, string y)
{
  if(x == null || y == null)
    throw new ArgumentNullException();
  int count = x.Length;
  if(count > y.Length)
    return FirstUnmatchedIndex(y, x);
  if(ReferenceEquals(x, y))
    return -1;
  for(idx = 0; idx != count; ++idx)
    if(x[idx] != y[idx])
      return idx;
  return count == y.Length? -1 : count;
}

这是一个简单的序数比较。不区分大小写的顺序比较是一个简单的更改,但是基于文化的比较很难定义;"Weißbier"与第二个字符串中最后一个S上的"WEISSBIERS"不匹配,但这算位置8还是位置9?

本主题是比较字符串并获得它们彼此不同的第一个位置的副本,其中包含使用Linq

的更好的一行解决方案。

可以编写像

这样的字符串扩展
public static class MyExtensions
{
    public static IList<char> Mismatch(this string str1, string str2)
    {
        var char1 = str1.ToCharArray();
        var char2 = str2.ToCharArray();
        IList<Char> Resultchar= new List<char>();
        for (int i = 0; i < char2.Length;i++ )
        {
            if (i >= char1.Length || char1[i] != char2[i])
                Resultchar.Add(char2[i]);
        }
        return Resultchar;
    }
}

一样使用
var r = "1234567890".Mismatch("1234567880");

这不是一个寻找不匹配的优化算法。

如果您只对查找第一个不匹配感兴趣,

public static Char FirstMismatch(this string str1, string str2)
        {
            var char1 = str1.ToCharArray();
            var char2 = str2.ToCharArray();             
            for (int i = 0; i < char2.Length;i++ )
            {
                if (i >= char1.Length || char1[i] != char2[i])
                    return char2[i];
            }
            return ''c;
        }

我的两分钱。这里只是一个比较两个字符串的循环,一个叫做ExpectedHexStringParameterValue,另一个叫做defaultHexStringParVal。当第一个不匹配时,循环中断。

int mismatchIndex = 0;
for (int i = 0; i <= ExpectedHexStringParameterValue.Length - 1; i++)
{
    Trace.WriteLine($"Go: {ExpectedHexStringParameterValue[i].ToString()}");
    if (i > defaultHexStringParVal.Length - 1)
      {
           mismatchIndex = i;
           break;
       }
    if (ExpectedHexStringParameterValue[i].ToString() != defaultHexStringParVal[i].ToString())
      {
           mismatchIndex = i;
           break;
      }
}