简体   繁体   English

检查字符串是否为子字符串C#的最快方法?

[英]Fastest way to check if a string is a substring C#?

I have a need to check if a list of items contains a string...so kind of like the list gets filtered as the user types in a search box. 我需要检查项目列表是否包含字符串...这样的列表就像在用户在搜索框中键入内容时被过滤一样。 So, on the text changed event, I am checking if the entered text is contained in one of the listox items and filtering out...so something like: 因此,在发生文本更改事件时,我正在检查输入的文本是否包含在listox项之一中并过滤掉……类似:

value.Contains(enteredText)

I was wondering if this is the fastest and most efficient way to filter out listbox items? 我想知道这是否是筛选列表框项目的最快,最有效的方法?

Is Contains() method the best way to search for substrings in C#? Contains()方法是在C#中搜索子字符串的最佳方法吗?

I'd say that in all but very exceptional circumstances, it's fast and efficient enough , and even in such exceptional circumstances it's likely to be a purely academical problem. 我要说的是,在非常例外的情况下,它足够快且有效,即使在这样的例外情况下,它也可能纯粹是学术问题。 If you use it and come across any bottlenecks in your logic related to this then I'd be surprised, but only then would it be worth looking at, then chances are you'll be looking elsewhere. 如果您使用它,并在与此相关的逻辑中遇到任何瓶颈,那么我会感到惊讶,但是只有到那时它才值得一看,然后您可能会在其他地方寻找。

Contains is one of the cheapest methods in my code completion filtering algorithm (Part 6 #6, where #7 and the fuzzy logic matching described in the footnote are vastly more expensive), which doesn't have problems keeping up with even a fast typing user and thousands of items in the dropdown. Contains是我的代码完成过滤算法中最便宜的方法之一(第6部分#6,其中脚注中描述的#7和模糊逻辑匹配要昂贵得多),即使快速键入也没有问题用户和下拉菜单中的数千个项目。

I highly doubt it will cause you problems. 我非常怀疑这会给您带来麻烦。

Although this is not the fastest option globally, it is the fastest one for which you do not need to code anything. 尽管这不是全局上最快的选项,但它是不需要编写任何代码的最快的选项。 It should be sufficient for filtering drop-down items. 它足以过滤下拉项。

For longer texts, you may want to go with the KMP Algorithm , which has a linear timing complexity. 对于较长的文本,您可能需要使用KMP算法 ,该算法具有线性时序复杂度。 Note, however, that it would not make any difference for very short search strings. 但是请注意,对于非常短的搜索字符串而言,它不会有任何区别。

For searches that have lots of matches (eg ones that you get for the first one to two characters) you may want to precompute a table that maps single letters and letter pairs to the rows in your drop-down list for a much faster look-up at the expense of using more memory (a pretty standard tradeoff in programming in general). 对于具有大量匹配项的搜索(例如,您从第一个到第二个字符获得的匹配项),您可能需要预先计算一个表,该表将单个字母和字母对映射到下拉列表中的行,以更快地查找-以使用更多内存为代价(通常是编程中相当标准的折衷)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM