C#中的字符串搜索与VB中的LIKE运算符有些相似



我知道有人问我这个问题。我并不是真的在寻找一个函数来做这件事。我希望能得到一些技巧,让我做得更好。基本上,拿一根长绳子,在里面找一根小绳子。我知道总有一百万种方法可以把事情做得更好,这就是我来到这里的原因。

请看一下代码片段,让我知道你的想法。不,它不是很复杂,是的,它确实能满足我的需求,但我更感兴趣的是了解痛点在哪里,我认为它会起作用,但出于某种原因不会。我希望这是有道理的。但是,为了给SO一个答案,这是执行这项任务的有力方法吗(我知道答案:(

对建设性的批评非常感兴趣,而不仅仅是";这太糟糕了;。我恳请你详细阐述这样一个想法,这样我才能充分利用这些回应。

public static Boolean FindTextInString(string strTextToSearch, string strTextToLookFor)
{
//put the string to search into lower case
string strTextToSearchLower = strTextToSearch.ToLower(); 
//put the text to look for to lower case
string strTextToLookForLower = strTextToLookFor.ToLower(); 
//get the length of both of the strings
int intTextToLookForLength = strTextToLookForLower.Length; 
int intTextToSearch = strTextToSearchLower.Length;
//loop through the division amount so we can check each part of the search text
for(int i = 0; i < intTextToSearch; i++) 
{
//substring at multiple positions and see if it can be found
if (strTextToSearchLower.Substring(i,intTextToLookForLength) == strTextToLookForLower) 
{
//return true if we found a matching string within the search in text
return true; 
}
}
//otherwise we will return false
return false; 
}

如果只关心在字符串中查找子字符串,只需使用String.Contains()

示例:

string string_to_search = "the cat jumped onto the table";
string string_to_find = "jumped onto";
return string_to_search.ToLower().Contains(string_to_find.ToLower());

您可以通过以下方式重用VB的Like运算符:

1( 参考Microsoft.VisualBasic.dll库。

2( 使用以下代码。

using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
if (LikeOperator.LikeString(Source: "11", Pattern: "11*", CompareOption: CompareMethod.Text)
{
// Your code here...
}

要以不区分大小写的方式实现函数,可能更适合使用IndexOf,而不是将两个ToLower()调用与Contains组合使用。这既是因为ToLower()将生成一个新字符串,也是因为土耳其问题。

下面这样的东西应该能起到作用,如果其中一个术语是null,它将返回False,否则将使用不区分大小写的IndexOf调用来确定搜索术语是否存在于源字符串中:

public static bool SourceContainsSearch(string source, string search)
{
return search != null &&
source?.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1;
}

最新更新