[英]loop through an array and find partial string
if i have array 如果我有阵列
array[0] = "jack"; array [0] =“jack”; array[1] = "jill";
array [1] =“jill”; array[2] = "lisa";
array [2] =“lisa”; array[2] = "jackie";
array [2] =“jackie”;
and i want to find all elements with "ack" in it. 我想找到所有带有“ack”的元素。
in this case it would return 在这种情况下它会返回
"jack", "jackie". “杰克”,“杰基”。
what is the fastest way of doing this? 这样做的最快方法是什么?
array.Where(s => s.Contains("ack"));
(高兴地忽略任何本地化/字符串排序/区分大小写问题。)
This should be a little bit faster than a LINQ solution. 这应该比LINQ解决方案快一点。
var list = new List<string>();
foreach(string s in array)
{
if ((s ?? "").Contains("ack"))
{
list.Add(s);
}
}
I don't really know C#. 我真的不知道C#。 Here is a basic low-level approach in pseudo-code:
这是伪代码中的基本低级方法:
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
Almost certainly contains bugs. 几乎肯定包含错误。
I believe this should be faster than the LINQ solution. 我相信这应该比LINQ解决方案更快。
IEnumerable<string> Containing(string[] xs, string sub) {
foreach(string s in array)
if (s.Contains(sub))
yield return s;
}
I am assuming no null strings in xs
. 我假设在
xs
没有空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.