[英]String array: search for text, return line number of first occurrence
In my string array, I want to look up some text and return the the line number of the first occurrence as an int. 在我的字符串数组中,我想查找一些文本并以int形式返回第一次出现的行号。
This is working; 这正在工作;
public static int LookUpLineNumber(String[] item, string TextToLookUp)
{
int m;
for (m = 0; m < item.Count(); m++)
{
if (item[m].Contains(TextToLookUp))
{
break;
}
}
return m++;
}
However, I am wondering if there is any way to optimize it for efficiency and length? 但是,我想知道是否有任何方法可以针对效率和长度进行优化?
Speed comparison: (average time on 10.000 runs with an string array of size 10.000) 速度比较:( 平均时间为10.000,使用大小为10.000的字符串数组运行)
Using my code: 使用我的代码:
Using Habib's code: Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));
使用Habib的代码: Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));
Your current solution looks OK. 您当前的解决方案看起来还可以。 You can have return m;
您可以return m;
instead of return m++
. 而不是return m++
。
If you want to shorten your code you can use Array.FindIndex<T>
like: 如果要缩短代码,可以使用Array.FindIndex<T>
例如:
public static int LookUpLineNumber(String[] item, string TextToLookUp)
{
return Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));
}
Not really sure if it would give you any performance gain. 不确定是否会为您带来任何性能提升。
If you need to do this multiple times, a suffix tree built out of the array would be the fastest approach: 如果您需要多次执行此操作,则从阵列中构建的后缀树将是最快的方法:
http://en.wikipedia.org/wiki/Suffix_tree http://en.wikipedia.org/wiki/Suffix_tree
However, if you are not re-using the array, then I think the approach you have is likely fastest, short of using a regex to do the contains, which may be faster if the regex is pre-compiled. 但是,如果您不重复使用数组,那么我认为您使用的方法可能最快,没有使用正则表达式来进行包含,如果正则表达式是预编译的,则可能更快。
You can also do the following :- 您还可以执行以下操作:
Array.FindIndex(item,i=>i.Contains(TextToLookUp));
The above would work even if it is not sorted. 即使未排序,以上内容仍然有效。
The above can be further optimized by using IndexOf
operations instead of Contains
and passing StringComparison.OrdinalIgnoreCase
. 通过使用IndexOf
操作而不是Contains
并传递StringComparison.OrdinalIgnoreCase
可以进一步优化上述内容。 Then you will have to compare it against 0. 然后,您必须将其与0进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.