zoukankan      html  css  js  c++  java
  • 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+"次"); } }
  • 相关阅读:
    linux内核(四)内存管理单元MMU
    open函数详解
    linux内核(三)文件系统
    C++中数字与字符串之间的转换 scanf string总结(复习必读)
    hello程序的运行过程-从计算机系统角度
    剑指offer第12题打印从1到n位数以及大整数加法乘法
    2017-10-11第二次万革始面经
    为什么需要半关闭
    Ubuntu指令
    143. Reorder List
  • 原文地址:https://www.cnblogs.com/YangGC/p/8462106.html
Copyright © 2011-2022 走看看