A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 rick1991chen 于 2015-4-22 17:47 编辑
  1. class StringTest3
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 String s = "ddaeyyyasdyyyilihyyypo";
  6.                 String key = "yyy";

  7.                 sop("count="+getSubCount(s,key));
  8.         }

  9.         public static int getSubCount(String s,String key)
  10.         {
  11.                 int count = 0;
  12.                 int index = 0;

  13.                 while ((index=s.indexOf(key))!=-1)
  14.                 {
  15.                         sop("s="+s);
  16.                         s = s.substring(index+s.indexOf(key));

  17.                         count++;
  18.                 }
  19.                 sop("s="+s);
  20.                 return count;
  21.         }

  22.         public static void sop(String s)
  23.                 {
  24.                         System.out.println(s);
  25.                 }
  26. }
复制代码
在自定义函数getSubCount()里,最后打印出的字符串s 是空的 如图!
求解!

StringTest3.JPG (15.12 KB, 下载次数: 0)

StringTest3.JPG

3 个回复

倒序浏览
问题出在23行,s此时是null吗?
回复 使用道具 举报
第1次循环
while ((index=s.indexOf(key))!=-1)//index=4
                {
                        sop("s="+s);
                        s = s.substring(index+s.indexOf(key));//s="sdyyyilihyyypo"

                        count++;
                }

第2次循环
s="sdyyyilihyyypo";
while ((index=s.indexOf(key))!=-1)//index=2
                {
                        sop("s="+s);
                        s = s.substring(index+s.indexOf(key));//s="yilihyyypo"

                        count++;
                }
第3次循环
s="yilihyyypo"
while ((index=s.indexOf(key))!=-1)//index=5
                {
                        sop("s="+s);
                        s = s.substring(index+s.indexOf(key));//s =s.substring(10) ="";

                        count++;
                }

结束循环,此时s=“”;
执行sop("s="+s)语句打印出s等于空字符串。
回复 使用道具 举报
刘辉林 发表于 2015-4-22 16:48
第1次循环
while ((index=s.indexOf(key))!=-1)//index=4
                {

高,明白了!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马