zoukankan      html  css  js  c++  java
  • Day_09【常用API】扩展案例8_计算字符'j'和字符串'java'在字符串中出现的次数

    需求说明

    •   定义如下字符串:
        String str = “javajfiewjavajfiowfjavagkljjava”;
        请分别定义方法统计出:
        	1.字符串中:字符j的数量
        	2.字符串中:字符串java的数量
      
    package com.itheima2;
    
    public class Test8 {
    	public static void main(String[] args) {
    		String str = "javajfiewjavajfiowfjavagkljjava";
    		char ch ='j';
    		String s = "java";
    		
    		int count = countChar(str, ch);
    		int count2 = countString(str, s);
    		System.out.println("字符"+ch+"一共出现了"+count+"次");
    		System.out.println("字符串"+s+"一共出现了"+count2+"次");
    	}
    
    	/*
    	 * 定义方法统计出字符串中:字符j的数量
    	 * 返回值类型:int count
    	 * 参数列表:String str,char ch
    	 */
    	public static int countChar(String str,char ch) {
    		int index = 0;
    		int count = 0;
    		while((index = str.indexOf(ch)) != -1){
    			count++;
    			str = str.substring(index + 1);
    		}
    		return count;
    	}
    	
    	/*
    	 * 定义方法统计出字符串中:字符串java的数量
    	 * 返回值类型:int count
    	 * 参数列表:String str,String s
    	 */
    	public static int countString(String str,String s) {
    		int index = 0;
    		int count = 0;
    		while((index = str.indexOf(s)) != -1) {
    			count++;
    			str = str.substring(index + 1);
    		}
    		return count;
    	}
    	
    }
    
    

    控制台内容
    在这里插入图片描述

  • 相关阅读:
    什么是内部类
    "=="和equals方法究竟有什么区别?
    SWFUpload乱码问题的解决
    xStream转换XML、JSON
    Java文件下载
    笔记摘录
    Javascript 函数传参问题
    JQUERY伸缩导航
    ruby关于flip-flop理解上一个注意点
    ruby 使用Struct场景
  • 原文地址:https://www.cnblogs.com/zzzsw0412/p/12772534.html
Copyright © 2011-2022 走看看