黑马程序员技术交流社区

标题: 统计一个字符串在某个字符串中出现的次数 [打印本页]

作者: 肚小糖    时间: 2015-8-25 15:48
标题: 统计一个字符串在某个字符串中出现的次数
  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. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2