如何在不显着影响性能的情况下将其重构为oneliner或至少某些本机函数?我将针对20个子字符串检查大约100个字符串。在使用5年的普通专业笔记本电脑上,这种情况不应持续超过200-300毫秒。
''' <summary>
''' Indicates whether the string includes at least one of the provided substrings.
''' </summary>
''' <param name="MyString">The string this extension applies to.</param>
''' <param name="SubStrings">The array of substrings that may be contained within the main string. Best performance when low index values contain the substrings the most likely to match.</param>
<System.Runtime.CompilerServices.Extension()>
Function ContainsAtLeastOneOf(MyString As String, SubStrings As String()) As Boolean
For Each SubString As String In SubStrings
If MyString.Contains(SubString) Then Return True
Next
Return False
End Function
我发现了许多解决方案,人们在其中检查一组字符串都包含相同的子字符串,但是找不到与之相反的主题。 我有几种解决方案,但似乎没有一种足够干净。我想必须有一种更明显的方法来实现这一目标。
目前,我能想到的选择是:
Text.RegularExpressions.Regex.IsMatch(MyString, string.format("{0}|{1}|{2}", SubStr1, SubStr2, SubStr3, ...))
If MyString.Contains(SubStr1) OrElse MyString.Contains(SubStr2) OrElse ...
IEnumerable.Intersect(...)
里有东西,但是那会在Char
而不是String
上循环。c#个答案是可以接受的。
答案 0 :(得分:2)
这个怎么样
Module Module1
Sub Main()
Const so = "StackOverFlow"
Dim t1 = Now
For i = 0 To 100
Console.WriteLine(so.ContainsAtLeastOneOf(New String() {"over1", "over"}, True))
Next
Console.WriteLine((Now - t1).TotalMilliseconds)
Console.ReadLine()
End Sub
<System.Runtime.CompilerServices.Extension()>
Function ContainsAtLeastOneOf(myString As String, subStrings As String(), Optional caseInsensitive As Boolean = False) _
As Boolean
If caseInsensitive Then
Return subStrings.Any(Function(subString) myString.ToLower().Contains(subString.ToLower()))
End If
Return subStrings.Any(Function(subString) myString.Contains(subString))
End Function
End Module