用C#进行字符串搜索有点类似于说VB的LIKE运算符

时间:2018-12-05 16:26:19

标签: c# string string-matching

我知道有人问过这个问题。而且我并不是真的在寻找可以这样做的功能。我希望获得一些技巧,使自己的方法变得更好。基本上,取一个长字符串,然后在其中搜索一个较小的字符串。我知道,实际上总是有上百万种方法可以使事情做得更好,这就是让我来到这里的原因。

请查看代码段,让我知道您的想法。不,它不是很复杂,是的,它确实可以满足我的需求,但是我对学习痛点将它用于我认为会起作用但不会出于这种原因的某些东西更感兴趣。我希望这是有道理的。但是给这个问题一个可以解决的方法,这是执行此任务的一种有效方法(我对答案有些了解:))

对建设性批评超级感兴趣,而不仅仅是“不好”。我恳请您详细阐述这种想法,以便我能充分利用答复。一如既往,谢谢高手。

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; 
}

3 个答案:

答案 0 :(得分:2)

如果您只想在字符串中查找子字符串,只需使用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());

答案 1 :(得分:1)

您可以通过以下方式重用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...
}

答案 2 :(得分:0)

要以不区分大小写的方式实现您的功能,使用val hasColor=color.map(_.id).contains(updated.id) newColorList = (hasColor,updated.quantity) match { case (true,0) => updated.copy(enddate = Instant.now().toEpochMilli) :: colors.filterNot(s => s.id == updated.id) case (true,_) => updated :: colors.filterNot(s => s.id == updated.id) otherwise => this } 而不是将两个IndexOf调用与ToLower()组合起来可能更合适。这是因为Contains将生成一个新字符串,也是因为the Turkish İ Problem

如下所示的方法应该可以解决问题:如果任一术语为ToLower(),则返回False,否则使用不区分大小写的null调用来确定搜索词是否存在于源字符串:

IndexOf