首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >c#字符串比较方法返回第一个不匹配的索引

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

Stack Overflow用户
提问于 2011-12-14 20:13:37
回答 5查看 7K关注 0票数 20

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

代码语言:javascript
复制
string A = "1234567890"

string B = "1234567880"

我想要得到一个返回值,它允许我看到匹配中断的第一个出现是A8

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-12-14 20:22:08

代码语言:javascript
复制
/// <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;
}
票数 7
EN

Stack Overflow用户

发布于 2011-12-14 20:19:30

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

代码语言:javascript
复制
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;
}
票数 2
EN

Stack Overflow用户

发布于 2011-12-14 20:22:56

据我所知没有,但这是相当微不足道的:

代码语言:javascript
复制
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?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8504266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档