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;
	}
	
}

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

posted @ 2019-12-17 02:21  _codeRookie  阅读(200)  评论(0编辑  收藏  举报