Loop through an array and find a partial string

if i have an array

array [0] = "jack"; array [1] = "jill"; array [2] = "lisa"; array [2] = "jackie";

and I want to find all elements with "ack" in it.

in this case it will return

"jack", "jackie".

What's the fastest way to do this?

+2


source to share


4 answers


array.Where(s => s.Contains("ack"));

      



(Harshly ignoring any localization / string / case sensitivity setting issues.)

+7


source


This should be slightly faster than a LINQ solution.



var list = new List<string>();
foreach(string s in array)
{
    if ((s ?? "").Contains("ack"))
    {
        list.Add(s);
    }
}

      

+1


source


I don't really know C #. Here's a basic low-level approach in pseudocode:

function boolean contains_string(string haystack, string needle)
  int needleIndex
  int haystackIndex
  for haystackIndex from 0 to haystack.length-needle.length
    for needleIndex from 0 to needle.length
      if haystack[haystackIndex+needleIndex] != needle[needleIndex]
        break
      end if
    end for
    if needleIndex == needle.length-1
      return TRUE
    end if
  end for
  return FALSE
end function

for each element in array
  if contains_string(element, "ack")
    new_array.push element
  end if
end for

      

It almost certainly contains errors.

0


source


I believe this should be faster than a LINQ solution.

IEnumerable<string> Containing(string[] xs, string sub) {
  foreach(string s in array)
  if (s.Contains(sub))
    yield return s;
}

      

I do not accept null strings in xs

.

0


source







All Articles