string str = "12333435";
统计“3”的数量返回4求代码如何写

解决方案 »

  1.   

    string str = "12333435";
    string subStr = "3";
    int len = str.Replace(subStr, "").Length / subStr.Length;
    Text = len.ToString();
      

  2.   

    我自己写的方法是:
            public int count3(int i)
            {   
                int count = 0;
                string str = i.ToString();
                for (int j = 0; j < str.Length; j++)
                {
                    if (str[j] == '3')
                        count++;
                }
                return count;
            }
    感觉写的不是很好,所以想问问大家,还有更简单的方法吗
      

  3.   

    //如果是整数可以通过取余判断
    public int count3(int i)
    {
        int Result = 0;
        while (i > 0)
        {
            if (i % 10 == 3) Result++;
            i = i / 10;
        }
        return Result;
    }
      

  4.   


    string str = "12333435";
    int num = System.Text.RegularExpressions.Regex.Matches(str, "3").Count;
      

  5.   

    string str = "12333435";
    string subStr = "3";
    string result = str.Length - str.Replace(subStr, string.Empty).Length;
      

  6.   

    string result = str.Length - str.Replace(subStr, string.Empty).Length;
    ----------------
    错了...copy的恶果...-_-#int result = str.Length - str.Replace(subStr, string.Empty).Length;要得到较高效率就不要用正则...不要用循环...
      

  7.   


    int i=0;
    foreach(char c in str)
        if (c=='3') i++;