有人问我这个问题。我并不是真的想要这样做的功能。我希望得到一些关于制作一个更好的方法的技巧。基本上,取一个长字符串,并在其中搜索一个较小的字符串。我知道总有百万种方法可以做得更好,这就是我带到这里的原因。
请查看代码段,并告诉我您的想法。不,它不是很复杂,是的,它确实能满足我的需求,但是我更感兴趣的是学习哪些痛点将用于我认为可以用的东西,但不会出于这样的原因。我希望这是有道理的。但是要给这个问题一个回答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()
将生成一个新的字符串,因为the Turkish İ Problem。
像下面这样的东西应该做的伎俩,如果任一项是False
它返回null
,否则使用不区分大小写的IndexOf
调用来确定源字符串中是否存在搜索项:
public static bool SourceContainsSearch(string source, string search)
{
return search != null &&
source?.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1;
}