题目:*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