如何在字符串中查找指定字符串出现的次数,或者直接返回次数个字符串例如字符串:“中国中国广州中国中国广东广东广州广东广东”
如果我查找:“广州”那我想要的结果是2(出现2次)或者能有什么方法返回2次“广州”字符串更好。急啊!那位能帮帮忙啊...............

解决方案 »

  1.   

    int GetCount(string all, string s)
    {
     int total = 0;
     int i = 0; while(i >= 0)

     i = all.IndexOf(s, i + s.Length);
     total ++;
     } return total;
    }
      

  2.   

    使用正则表达式
    string strInput = "例如字符串:“中国中国广州中国中国广东广东广州广东广东”";
    string regexStr = "广州";
    Regex.Matches(strInput, regexStr).Count; //2
      

  3.   

    或者":
    string all = "中国中国广州中国中国广东广东广州广东广东";int count = (all.Length - all.Replace("广州", "")) / "广州".Length
      

  4.   

    using System;
    using System.Text.RegularExpressions;//需要这个引用main()函数
    {
        string strInput = "例如字符串:“中国中国广州中国中国广东广东广州广东广东”";
        string regexStr = "广州";
        Console.WriteLine(Regex.Matches(strInput, regexStr).Count); //2
        Console.ReadLine();
    }正则真方便