繁体   English   中英

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

[英]Check if string contains substring more than once

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

为了优化这一点:对我来说,知道有多个结果而不是多少结果就足够了。

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

string s = "tytyt";

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

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

RegEx的一行代码:

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

您可以使用以下使用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

演示

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

您也可以使用Regex类。 msdn正则表达式

   int count;
   Regex regex = new Regex("your search pattern", RegexOptions.IgnoreCase);
   MatchCollection matches = regex.Matches("your string");
   count = matches.Count;
private bool MoreThanOnce(string full, string part)
{
   var first = full.IndexOf(part);
   return first!=-1 && first != full.LastIndexOf(part);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM