Java语言程序设计基础篇_编程练习题*18.15 (字符串中某个指定字符出现的次数)

题目:*18.15 (字符串中某个指定字符出现的次数)

使用辅助方法改写编程练习题18.10,将子串的high下标传递给这个方法。辅助方法头为:

public static int count(String str,char a,int high)
  • 代码示例 

编程练习题18_15CharacterCount.java

package chapter_18;

import java.util.Scanner;

public class 编程练习题18_15CharacterCount {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a string and a character: ");
		String str = input.next();
		char ch = input.next().charAt(0);
		System.out.println(count(str, ch));
		input.close();
	}
	public static int count(String str,char a) {
		return count(str, a,str.length()-1);
	}
	public static int count(String str, char a, int high) {  
        if (high < 0) {  
            return 0; // 基本情况:如果high小于0,返回0  
        }  
        int count = 0; // 局部变量来计数,避免使用静态变量  
        if (str.charAt(high) == a) {  
            count++;  
        }  
        return count + count(str, a, high - 1); // 递归调用并累加结果  
    }  
}
  •  输出结果
Enter a string and a character: aaafdasddaa a
6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值