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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

要求: 获取一个字符串在另一个字符串中出现的次数
  例如字符串"kk"在字符串"abkkcdkkefkkskk"中出现的次数
  思路:   1. 定义个计数器;
                 2. 获取kk第一次出现的位置;
                 3. 从第一次出现位置后剩余的字符串中继续获取kk出现的位置,每获取一次就计数一次;
                 4. 当获取不到时,计数完成。
实现试例:
  1. public class StringTest3 {
  2.         //实现方式一
  3.         public static int getSubCount(String str, String key) {
  4.                 int count = 0;
  5.                 int index = 0;

  6.                 while ((index = str.indexOf(key)) != -1) {
  7.                         sop("str=" + str);
  8.                         str = str.substring(index + key.length());

  9.                         count++;
  10.                 }
  11.                 return count;
  12.         }

  13.         //实现方式二
  14.         public static int getSubCount_2(String str, String key) {
  15.                 int count = 0;
  16.                 int index = 0;

  17.                 while ((index = str.indexOf(key, index)) != -1) {
  18.                         sop("index=" + index);
  19.                         index = index + key.length();

  20.                         count++;
  21.                 }
  22.                 return count;
  23.         }

  24.         public static void main(String[] args) {
  25.                 String str = "kkabkkcdkkefkks";

  26.                 // /sop("count====="+str.split("kk").length);不建议使用。

  27.                 sop("count=" + getSubCount_2(str, "kk"));
  28.         }

  29.         public static void sop(String str) {
  30.                 System.out.println(str);
  31.         }
  32. }
复制代码


0 个回复

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