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

发布于 2024-12-20 23:16:03 字数 177 浏览 1 评论 0原文

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

string A = "1234567890"

string B = "1234567880"

我想返回一个值,该值允许我看到匹配中断的第一次出现是 A[8]

Is there an exsting string comparison method that will return a value based on the first occurance of a non matching character between two strings?

i.e.

string A = "1234567890"

string B = "1234567880"

I would like to get a value back that would allow me to see that the first occurance of a matching break is A[8]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

放血 2024-12-27 23:16:03
/// <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;
}
/// <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;
}
提笔书几行 2024-12-27 23:16:03

如果您安装了 .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();

If you have .net 4.0 installed, this could be a way:

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

edit:

Though, if you need the position:

    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();
執念 2024-12-27 23:16:03

如下所示的扩展方法可以完成这项工作:

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

An extension method along the lines of the below would do the job:

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;
}
迷乱花海 2024-12-27 23:16:03

据我所知,但这非常简单:

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?

Not that I know of, but it's pretty trivial:

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

This is a simple ordinal comparison. Ordinal case-insensitive comparison is an easy change, but culture-base is tricky to define; "Weißbier" mismatches "WEISSBIERS" on the final S in the second string, but does that count as position 8 or position 9?

帅气尐潴 2024-12-27 23:16:03

本主题与比较字符串重复并获得彼此不同的第一个位置,其中包含使用 Linq 的更好的单行解决方案

This topic is a duplicate of Comparing strings and get the first place where they vary from eachother, which contains a better, one line, solution using Linq

辞旧 2024-12-27 23:16:03

可以编写字符串扩展,如

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

Use it like

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

It possible to write string extension like

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

Use it like

var r = "1234567890".Mismatch("1234567880");

It is not an optimized algorithm for finding the mismatch.

If you are interested only to find the the first mismatch,

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;
        }
童话里做英雄 2024-12-27 23:16:03

我的两分钱。
这里只是一个循环,比较两个字符串,一个名为 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;
      }
}

My two cents.
Here just a loop comparing the two strings one called ExpectedHexStringParameterValue and the other called defaultHexStringParVal. The loop just break with the first mismatch.

int mismatchIndex = 0;
for (int i = 0; i <= ExpectedHexStringParameterValue.Length - 1; i++)
{
    Trace.WriteLine(
quot;Go: {ExpectedHexStringParameterValue[i].ToString()}");
    if (i > defaultHexStringParVal.Length - 1)
      {
           mismatchIndex = i;
           break;
       }
    if (ExpectedHexStringParameterValue[i].ToString() != defaultHexStringParVal[i].ToString())
      {
           mismatchIndex = i;
           break;
      }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文