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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

如下代码是求出了“nba”在整串中出现的次数,但是我也想输出“nba”每次出现的在整串中位置index,怎么输出(结果0,5,10,16,20)
class  StringTest
{
        public static void main(String[] args)
        {
                String s="nbaernbatynbauianbapnba";
                String key="nba";
                int count=getKeyStringCount(s,key);
                System.out.println("key count:"+count);
        }
        public static int getKeyStringCount(String str,String key)
        {
                //String str=new String();
                int count=0;//定义key出现的次数
                int index=0;//定义key出现的位置
                while((index=str.indexOf(key))!=-1)
                {                              
               
                        str=str.substring(index+key.length());//生成剩余的字符串
                        count++;
                       
                        //System.out.println("index="+index);
                }
                return count;
               
        }
}

2 个回复

倒序浏览
  1. while((index=str.indexOf(key,index))!=-1)
  2.              {
  3.                      System.out.println("index="+index);
  4.                      index=+index+key.length();
  5.                  count++;
  6.                      
  7.                     
  8.              }
复制代码

把判断while循环条件的语句改变一下就好了
回复 使用道具 举报
三分之一 发表于 2015-8-16 15:34
把判断while循环条件的语句改变一下就好了

噢  原来是这样 谢谢了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马