Comparing strings and get the first place where they vary from eachother

后端 未结 8 1147
滥情空心
滥情空心 2020-12-16 11:07

I want to get the first place where 2 string vary from each other. example: for these two strings: \"AAAB\" \"AAAAC\"

I want to get the result 4.

How do i d

8条回答
  •  甜味超标
    2020-12-16 12:01

    You can create an extension method to do the trick:

    public static class StringExtensions {
        public static int IndexOfDifferenceFrom(this string source, string compareTo)
        {
            for(var i = 0; i < source.Length && i < compareTo.Length; ++i) {
                if (source[i] != compareTo[i]) {
                    return i;
                }
            }
    
            return source.Length < compareTo.Length ? source.Length : compareTo.Length;
        }
    
    }
    

    Or, for a LINQy solution:

    var index = string1.Where((ch, i) => string2[i] == ch).Select((ch, i) => i).DefaultIfEmpty(-1).First();
    

提交回复
热议问题