输入一个字符串,再输入要查找的字符, * 判断该字符在该字符串中出现的次数

需求说明

  • 输入一个字符串,再输入要查找的字符,
  • 判断该字符在该字符串中出现的次数

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(“请输入一个字符串:”);
String words = input.next();
System.out.print(“请输入要查找的字符:”);
String search = input.next();
// 转换字符串为字符数组
// char[] charArray = words.toCharArray();
// 循环查找,查找出,截断0-当前索引的
// 计数search在字符串中出现的次数
int count = 0;
// 声明一个字符串副本用来截断查找
String copyWords = words;
// 循环查找
while(true) {
// 如果副本字符能找到要搜索的字符返回索引值
int index = copyWords.indexOf(search);
// 判断能找到要搜索的字符是否能找到
if (index != -1) {
// 找到了,就截取索引值到字符串末尾的字符进行下一次循环查找
copyWords = copyWords.substring(index+1, copyWords.length());
// 计数
count++;
}else {
System.out.println(“查找完成!”);
break;
}
}
System.out.println("""+words+"“中包含”+count+“个”"+search+""");
}

}

猜你喜欢

转载自blog.csdn.net/Javastudenthhhk/article/details/89473070