born2fr4g
born2fr4g

Reputation: 1300

c# - search a string array using strings from another string array

Just like in the title. I got one array of strings and second array of strings. I want to display result in this kind of pattern: first element of the first array - then all elements from second array that occurs in first element of first array. After that second element of first array and all elements from second array that occurs in second element of first array. And so on. For example:

string[] arrayA = {"Lorem ipsum dolor sit amet, justo", "notgin like good cold beer"};
string[] arrayB = {"justo","beer","lorem"}
for (int i = 0; i < arrayA.Length; i++)
   {
      Console.WriteLine(arrayA[i]);

       for (int j = 0; j < arrayB.Length; j++)
       {
          int controlIndex = arrayA[i].IndexOf(arrayB[j]);
          if (controlIndex != -1)
          {
               Console.Write(" :--contains-->" + arrayB[j]);
          }

    }

}

So the result should looks like this:

But mine result is: - Lorem ipsum dolor sit amet, justo :--contains--> justo - notgin like good cold beer :--contains--> beer.

So as you can see there is no lorem listed

Upvotes: 2

Views: 3463

Answers (8)

Deepak Mandal
Deepak Mandal

Reputation: 1

 bool oupt ;
 string[] strarray1 = new string[3]{"abc","def","ghi" };
 string[] strarray2 = new string[4] { "648", "888", "999", "654" };
 if (strarray1.All(strarray.Contains))
    oupt = true;
 else
    oupt = false;

Upvotes: -1

Ram
Ram

Reputation: 49

I have given you all the possible answers , but the contains method will create a problem that it will also return true in the case as below mentioned.

reference_string = "Hello Stack Overflow"
test_string = "Over"

so try to avoid contains because contains method will

"Returns a value indicating whether the specified System.String object occurs within the this string"

Note: the StringComparer.OrdinalIgnoreCase is added for case insensitive.

/// <summary>
        /// Compares using binary search
        /// </summary>
        /// <param name="input"> search input</param>
        /// <param name="reference"> reference string</param>
        /// <returns> returns true or false</returns>
        public bool FatMan(string input, string reference)
        {
            string[] temp = reference.Split();
            Array.Sort(temp);
            List<string> refe = new List<string> { };
            refe.AddRange(temp);

            string[] subip = input.Split();
            foreach (string str in subip)
            {
                if (refe.BinarySearch(str, StringComparer.OrdinalIgnoreCase) < 0)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// compares using contains method
        /// </summary>
        /// <param name="input"> search input</param>
        /// <param name="reference"> reference string</param>
        /// <returns> returns true or false</returns>
        public bool Hiroshima(string input, string reference)
        {
            string[] temp = reference.Split();
            Array.Sort(temp);
            List<string> refe = new List<string> { };
            refe.AddRange(temp);
            string[] subip = input.Split();

            foreach (string str in subip)
            {
                if (!refe.Contains(str, StringComparer.OrdinalIgnoreCase))
                {
                    return false;
                }
            }

            return true;
        }


        public bool Nakashaki(string input, string reference)
        {
            string[] temp = reference.Split();
            Array.Sort(temp);
            List<string> refe = new List<string> { };
            refe.AddRange(temp);
            string[] subip = input.Split();

            int result = (from st in subip where temp.Contains(st, StringComparer.OrdinalIgnoreCase) select st).Count();

            if (result <= 0)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// compares using contains method
        /// </summary>
        /// <param name="input"> search input</param>
        /// <param name="reference"> reference string</param>
        /// <returns> returns true or false</returns>
        public bool LittleBoy(string input, string reference)
        {
            string[] subip = input.Split();
            foreach (string str in subip)
            {
                if (!reference.Contains(str))
                {
                    return false;
                }
            }

            return true;
        }

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

This is not hard at all if you break your problem down some. First of all, get away from dealing with arrays and indexes into them. Just use IEnumerable<T>, it will make your life easier.

Here's how I see it:

First, you want to find all strings from an array needles, that are part of a string, haystack.

public static IEnumerable<string> MatchingStrings(string haystack, IEnumerable<string> needles)
{
    return needles.Where(needle => haystack.Contains(needle));
}

This will return an IEnumerable of all of the strings from needles that are a part of haystack.

Then, you want to simply iterate over all of your search strings, I'll call that haystacks.

    static void Main(string[] args)
    {
        var haystacks = new[] {
            "Lorem ipsum dolor sit amet, justo",
            "notgin like good cold beer"
        };

        var needles = new[] {"justo", "beer", "lorem"};

        foreach (var haystack in haystacks) {
            Console.Write(haystack + "  contains --> ");
            var matches = MatchingStrings(haystack, needles);

            Console.WriteLine(String.Join(",", matches));
        }

        Console.ReadLine();
    }

Note that String.Contains() is case-sensitive. So "Lorem" will not match "lorem". If you want this behavior, you will have to convert them to lowercase first.

public static IEnumerable<string> MatchingStringsCaseInsensitive(string haystack, IEnumerable<string> needles)
{
    var h = haystack.ToLower();
    return needles.Where(needle => h.Contains(needle.ToLower()));
}

Upvotes: 2

Toby
Toby

Reputation: 647

Lorem is capitalized. Try using a case-insensitive search: .indexOf(string, StringComparison.CurrentCultureIgnoreCase)

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

foreach(var a in arrayA)
{
    Console.WriteLine("a: " + a);
    Console.WriteLine("bs: " + 
        String.Join(", ", arrayB.Where(b => a.IndexOf(b) > -1)));
}

Also if you mean to not care about case, a.IndexOf(b) would be a.IndexOf(b, StringComparison.OrdinalIgnoreCase).

Upvotes: 1

Kane
Kane

Reputation: 16802

Here's my attempt

string[] arrayA = {"lorem ipsum dolor sit amet, justo", "notgin like good cold beer"};
string[] arrayB = {"justo", "beer", "lorem"};

foreach (var item in from a in arrayA from b in arrayB where a.Contains(b) select new {a, b})
{
    Console.WriteLine(item.a);
    Console.WriteLine(item.b);
}

Note: Contains is a case sensitive compare and you'll need to write a custom comparer (as other answers have already done)

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460118

This is the Linq solution:

var result = arrayA.Select(a => new{
    A = a,
    bContains = arrayB.Where(b => a.IndexOf(b, 0, StringComparison.CurrentCultureIgnoreCase) > -1)            
});

foreach(var x in result)
{
    Console.WriteLine("{0}:--contains-->{1}", x.A, string.Join(",", x.bContains));
}

Here's a demo: http://ideone.com/wxl6I

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14522

string[] arrayA = {"Lorem ipsum dolor sit amet, justo", "notgin like good cold beer"};
string[] arrayB = {"justo","beer","lorem"};

foreach (var s in arrayA)
{
    Console.Write(s + " contains: " +
                  string.Join(",", arrayB.Where(s.Contains)));
}

And if you want to ignore case:

foreach (var s in arrayA)
{
    Console.Write(s + " contains: " +
                  string.Join(",", arrayB.Where(x =>
                      s.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1)));
}

Upvotes: 1

Related Questions