[英]How can i find the cardinal of the intersection, character wise, between two strings?
I am working on a project that requires some string manipulation and i need some help. 我正在开发一个需要一些字符串操作的项目,我需要一些帮助。
Say i have two strings: 说我有两个字符串:
string1 = "1 2 3 4 5";
string2 = "1 2 4 6 7";
This is actually what most of the strings I will be working with look like. 这实际上是我将使用的大多数字符串的样子。
I would like to know what is a smart, modern method, if any, to find the number of intersection between string of this type, something idealy like this: 我想知道什么是智能的,现代的方法,如果有的话,找到这种类型的字符串之间的交集数,理想情况如下:
//a way to create GetCardinal is what I am looking for
int cardinal = GetCardinal(string1, string2);
//Cardinal should be 3 as the intersection is "1 2 4"
I am mainly interested in methods that work great for the type of inputs like string1 and string2, meaning sequences of numbers separated by blank spaces 我主要对那些对输入类型有效的方法感兴趣,比如string1和string2,这意味着用空格分隔的数字序列
The reason for not using a List of int's is because the strings are output values and I am expecting some character outputs as well. 不使用int的原因是因为字符串是输出值,我也期待一些字符输出。
Thank you, Ciprian 谢谢你,西普里安
String.Split
, String.Join
and a little bit of LINQ ( Intersect
) will do the job: String.Split
, String.Join
和一点LINQ( Intersect
)将完成这项工作:
var result = String.Join(" ", string1.Split(' ').Intersect(string2.Split(' ')));
If you just need number of elements in the intersection, use Count
: 如果您只需要交叉点中的元素数量,请使用Count
:
var cardinal = string1.Split(' ').Intersect(string2.Split(' ')).Count();
你必须用空格分割它们,然后你可以使用Intersect
+ Count
:
int cardinal = string1.Split().Intersect(string2.Split()).Count();
You can use the split function of string plus some Linq 你可以使用string的split函数加上一些Linq
int GetCardinal(string s1, string s2)
{
return s1.Split(' ').Intersect(s2.Split(' ')).Count();
}
or if you could have multiple spaces or tabs: 或者如果您可以有多个空格或制表符:
int GetCardinal(string s1, string s2)
{
char []separators = new char[] { ' ', '\t' };
return s1.Split(separators, StringSplitOptions.RemoveEmptyEntries).Intersect(s2.Split(separators, StringSplitOptions.RemoveEmptyEntries)).Count();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.