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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. public class StringTest{
  2.         public static void main(String[] args){
  3.                 String str = "nbaernbatynbauinbaopnba";
  4.                 String key = "nba";
  5.                 int count = getKeyStringCount(str, key);
  6.                 System.out.println("count = "+count);
  7.         }
  8.         public static int getKeyStringCount(String str, String key){
  9.                 int count = 0;
  10.                 int index = 0;
  11.                 //用indexOf获取字串在字符串中出现的位置,如果找不到返回-1,跳出while循环
  12.                 while((index = str.indexOf(key))!=-1){
  13.                         //每找到一个字串,就把剩余字符串(substring(出现位置+子串的长度))赋给str变量,继续查找str。
  14.                         str = str.substring(index + key.length());
  15.                         count ++ ;
  16.                 }
  17.                 return count;
  18.         }
  19. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马