解决方案 »

  1.   

    使用substring 截取,比如第一个indexof的值是2  那么就截取 从2到最后的字符,再使用indexof取值,记录次数,,,,依次类推。
      

  2.   

    用的话,需要动态改变字符串的内容,比如找到一个后,字符串要变成从找到位置开始往后的剩余字符串,然后再用indexof,循环便可
      

  3.   


     string sTest = "abdfd-asdfsadf-sdfsdafsad-sadf";
                int iCount = 0;
                int pos = 0;
                do
                {
                    pos = sTest.IndexOf('-', pos);
                    pos++;
                    iCount++;
                } while (pos!=-1);iCounty就是次数了
      

  4.   

    条件需要改成pos!=0,而且结果是iCount-1.
      

  5.   

    namespace _1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int countOne = 0;
                Console.WriteLine("请输入一个字符串:");
                string strWord = Console.ReadLine();
                Console.WriteLine("请输入一个子字符:");
                char chr = Convert.ToChar(Console.ReadLine());            //使用indexOf的重载函数
                int index = 0;
                index = strWord.IndexOf(chr, index);//从下标为index处开始查找,有返回下标,无返回-1
                while (index != -1)
                {
                    index = strWord.IndexOf(chr, index+1);
                    countOne++;
                }
                Console.WriteLine("字符{0}在字符串中出现的了{1}次!", chr, countOne);
                Console.ReadKey();
            }
        }
    }
      

  6.   

    循环条件错误,用了pos++.pos就不会等于-1了,会死循环的
      

  7.   

    根据一楼朋友的提示,我用截取字符串Substring()完成了本道题目的统计次数。代码如下:
    namespace 书本练习题
    {
        class Program
        {
            static void Main(string[] args)
            {
                int countOne = 0;
                Console.WriteLine("请输入一个字符串:");
                string strWord = Console.ReadLine();
                Console.WriteLine("请输入一个子字符:");
                char chr = Convert.ToChar(Console.ReadLine());
     
                //使用substring()截取字符串
                int index = 0;
                do
                {
                    
                    index = strWord.IndexOf(chr);  //取字符Chr出现的下标
                    int End = strWord.Length - 1;  //取字符串strWord最后字符的下标
                    strWord = strWord.Substring(index+1, End - index);//截取从下标+1处开始到结尾的字符串
                    if (index != -1)
                    {
                        countOne++;//进入累加器累加一次,当最后没有出现chr时,不进入累加器
                    }                
                } while (index != -1);
                Console.WriteLine("字符{0}在字符串中出现的了{1}次!", chr, countOne);
                Console.ReadKey();
            }
        }
    }本道题目,我也学会了最优方法,就是5楼的方法。最后,再次感谢楼上的各位朋友。谢谢!