String/StringBuilder 类 统计字符串中字符出现的次数

1.1. 训练描述:【方法、String类】

一、需求说明:定义如下字符串:

String str = “javajfiewjavajfiowfjavagkljjava”;

二、请分别定义方法统计出:

  1. 字符串中:字符j的数量
  2. 字符串中:字符串java的数量
  3. 定义MainApp类,包含main()方法;
  4. 在MainApp类中,定义以下两个方法:

1.2. 操作步骤描述

  1)         可以统计一个字符串中,某个字符出现的次数;

      public static int countChar(String str,char c)

      

       /*核心代码:
        int index = 0; int count = 0; while((index = str.indexOf(c)) != -1){ count++; str = str.substring(index + 1); }
    利用indexOf()方法,进而改变字符串的方式来判断字符串的某字符出现的次
数;*/
 

  2)         可以统计一个字符串中,某个字符串出现的次数;

      public static int countString(String str,String s)

  1. 请实现方法,并在main()方法中分别调用这两个方法进行统计。
public class Task02 {
        public static void main(String[] args) {
            String str = "jfiewjavajfiowfgkljjava";
            System.out.println(str.toString());
            getCount(str,'j');
            getCount(str,"fi");
        }
        

          //用重载的方式计算字符以及字符串出现的次数
        public static void getCount(String str,char c){
            int index = 0;
            int count = 0;
            while((index = str.indexOf(c)) != -1){
                count++;
                str = str.substring(index + 1);
            }
            System.out.println(c +"共出现了"+count+"次");
        }
public static void getCount(String str,String c){ int index = 0; int count = 0; while((index = str.indexOf(c)) != -1){ count++; str = str.substring(index + 1); } System.out.println(c +"共出现了"+count+"次"); } }
原文地址:https://www.cnblogs.com/YangGC/p/8462106.html