Click here to Skip to main content
15,895,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I hae one odd query regarding strings.

Eg.
C#
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
C#
s1="I1,I2";

and
C#
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
C#
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
Posted
Updated 18-Mar-13 23:14pm
v2

1 solution

Well, assuming order is not important, you may use split and then perform a check on all the components of the s1 array, namely:
C#
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");
}
 
Share this answer
 
Comments
Orcun Iyigun 19-Mar-13 5:42am    
Answered faster than me :) 5ed.
krunalpanchalN 26-Mar-13 8:19am    
Yaa...great thanks a lot .. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900