包含子串问题的字符串 [英] String containing substring problem
问题描述
大家好,
我有一个关于字符串的奇怪查询。
例如。
我有字符串 s1 = I1,I2\" 跨度>;
string s2 = I1,I2, I3\" 跨度>;
bool result = s2.contains(s1);
代码有效罚款并给出真实结果,因为s2包含s1
但是当我有
s1 = I1,I2;
和
s2 = I1,I3,I2;
此时我卡住了,因为s2包含I1,I3,I2。
我想检查两个项目是否存在,无论位置如何。
我也尝试过使用Linq使用Array
s2.Intersect(s1).Any()
但是如果s2包含I1,I3,I5那么它也会将结果显示为true ...但我想检查这两个元素是否存在......在任何位置......
请帮助
问候,
Krunal Panchal
我们ll,假设订单不重要,您可以使用拆分然后对s1
数组的所有组件执行检查,即:
< pre lang =cs> string s1 = I1 ,I2\" 跨度>;
string s2 = I1,I3, I2\" 跨度>;
string [] a1 = s1.Split( new char [] {' ,'});
string [] a2 = s2.Split( new char [] {' ,'});
int matches = 0 ;
foreach ( string i1 in a1)
foreach ( string i2 in a2)
{
if (i1 == i2)
{
匹配++;
break ;
}
}
如果(匹配== a1.Count())
{
控制台。 WriteLine( s1项目在s2);
}
else
{
Console.WriteLine( s1项不在s2);
}
Hello everyone,
I hae one odd query regarding strings.
Eg.
I have string s1="I1,I2";
string s2="I1,I2,I3";
bool result=s2.contains(s1);
the code works fine and gives true result as s2 contains s1
but when i have
s1="I1,I2";
and
s2="I1,I3,I2";
at this point i m stuck, because s2 contains I1, I3, I2.
I want to check if there exists both the items irrespective of the location.
I have also tried it with Array using Linq
s2.Intersect(s1).Any()
but here if s2 contains I1,I3,I5 then also it gives result as true...but i want to check if the both elements exists or not...on any location..
Please help
Regards,
Krunal Panchal
Well, assuming order is not important, you may use split and then perform a check on all the components of thes1
array, namely:
string s1 = "I1,I2"; string s2 = "I1,I3,I2"; string[] a1 = s1.Split(new char[] { ',' }); string[] a2 = s2.Split(new char[] { ',' }); int matches = 0; foreach (string i1 in a1) foreach (string i2 in a2) { if (i1 == i2) { matches++; break; } } if (matches == a1.Count()) { Console.WriteLine("s1 items are in s2"); } else { Console.WriteLine("s1 items are NOT in s2"); }
这篇关于包含子串问题的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!