本文介绍了检查字符串是否包含列表中的元素(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码块:

For I = 0 To listOfStrings.Count - 1
    If myString.Contains(lstOfStrings.Item(I)) Then
        Return True
    End If
Next
Return False

输出为:

案例1:

myString: C:\Files\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: True

案例2:

myString: C:\Files3\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: False

列表(listOfStrings)可能包含多个项目(最少20个),并且必须对照数千个字符串(例如myString)进行检查.

The list (listOfStrings) may contain several items (minimum 20) and it has to be checked against a thousands of strings (like myString).

是否有更好(更有效)的代码编写方式?

Is there a better (more efficient) way to write this code?

推荐答案

使用LINQ,并使用C#(这些天我不太了解VB):

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

或(更简短,更有效,但可以说不够清晰):

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

如果您正在测试相等性,那么值得研究一下HashSet等,但这对部分匹配没有帮助,除非您将其拆分成多个片段并增加了复杂度.

If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.

update:如果您的意思是"StartsWith",则可以对列表进行排序并将其放入数组中;然后使用Array.BinarySearch查找每个项目-通过查找检查它是完全匹配还是部分匹配.

update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

这篇关于检查字符串是否包含列表中的元素(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:30