计数使用LINQ两个字符串之间匹配字符 [英] Count matching characters between two strings using LINQ

查看:464
本文介绍了计数使用LINQ两个字符串之间匹配字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个朋友问我如何改进一些代码使用LINQ。你会怎么做两个字符串之间的字符比较字符的指数来算匹配的数量?这里的原代码,可以将其与LINQ改进?



 私人诠释健身(串个体,目标字符串)
{
INT总和= 0;
的for(int i = 0; I< individual.Length;我++)
如果(个体[I] ==目标[I])总和++;
收益总和;
}


解决方案

 返回Enumerable.Range(0,individual.Length)
.Count之间(I =>个别[I] ==目标[I]);

一个更加万无一失的方法是(上面的代码会失败,如果目标个人)短:

 返回Enumerable.Range(0,Math.Min(individual.Length,target.Length))
.Count之间(I =>个别[I] ==目标[I]);






我相信该代码是正确的,因为是。 Enumerable.Range 方法有两个参数。其中第一个是开始索引(应该是 0 ),二是项目的数量。完整的代码片段,以测试并确保:

 类节目{
静态无效的主要(字串[] args) {
Console.WriteLine(健身(你好,世界));
}
静态INT健身(串个体,目标字符串){
返回Enumerable.Range(0,Math.Min(individual.Length,target.Length))
.Count之间(I =>个别[I] ==目标[I]);
}
}


A friend asked me how to improve some code with LINQ. How would you do a character by character comparison between two strings to count the number of matches at an index? Here's the original code, could it be improved with LINQ?

private int Fitness(string individual, string target)
   {
       int sum = 0;
       for (int i = 0; i < individual.Length; i++)
           if (individual[i] == target[i]) sum++;
       return sum;
   }

解决方案

return Enumerable.Range(0, individual.Length)
                 .Count(i => individual[i] == target[i]);

A more fool-proof way would be (the above snippet will fail if target is shorter than individual):

return Enumerable.Range(0, Math.Min(individual.Length, target.Length))
                 .Count(i => individual[i] == target[i]);


I believe the code is correct as is. Enumerable.Range method takes two arguments. The first of which is the start index (should be 0), the second is the count of items. The complete code snippet to test and make sure:

class Program {
  static void Main(string[] args) {
      Console.WriteLine(Fitness("hello", "world"));
  }
  static int Fitness(string individual, string target) {
      return Enumerable.Range(0, Math.Min(individual.Length, target.Length))
                       .Count(i => individual[i] == target[i]);
  }
}

这篇关于计数使用LINQ两个字符串之间匹配字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆