检查字符串是否包含多次子字符串

时间:2013-02-20 16:30:40

标签: c# search

要在字符串中搜索子字符串,我可以使用contains()函数。 但是,如何检查字符串是否包含多个子字符串?

要优化:对我而言,知道有多个结果而不是多少结果就足够了。

5 个答案:

答案 0 :(得分:11)

尝试利用快速IndexOfLastIndexOf字符串方法。使用下一个代码段。想法是检查第一个和最后一个索引是否不同,如果第一个索引不是-1,这意味着字符串存在。

string s = "tytyt";

var firstIndex = s.IndexOf("tyt");

var result = firstIndex != s.LastIndexOf("tyt") && firstIndex != -1;

答案 1 :(得分:3)

您可以使用以下使用string.IndexOf的扩展方法:

public static bool ContainsMoreThan(this string text, int count, string value,  StringComparison comparison)
{
    if (text == null) throw new ArgumentNullException("text");
    if (string.IsNullOrEmpty(value))
        return text != "";

    int contains = 0;
    int index = 0;

    while ((index = text.IndexOf(value, index, text.Length - index, comparison)) != -1)
    {
        if (++contains > count)
            return true;
        index++;
    }
    return false;
}

以下列方式使用它:

string text = "Lorem ipsum dolor sit amet, quo porro homero dolorem eu, facilisi inciderint ius in.";
bool containsMoreThanOnce = text.ContainsMoreThan(1, "dolor", StringComparison.OrdinalIgnoreCase); // true

Demo

这是一个字符串扩展,可以传递count,您搜索的valueStringComparison(例如,搜索不区分大小写)。

答案 2 :(得分:3)

使用RegEx的一行代码:

return Regex.Matches(myString, "test").Count > 1;

答案 3 :(得分:2)

您也可以使用Regex类。 msdn regex

   int count;
   Regex regex = new Regex("your search pattern", RegexOptions.IgnoreCase);
   MatchCollection matches = regex.Matches("your string");
   count = matches.Count;

答案 4 :(得分:0)

private bool MoreThanOnce(string full, string part)
{
   var first = full.IndexOf(part);
   return first!=-1 && first != full.LastIndexOf(part);
}
相关问题