package com.lb.commonclass.exer;
import java.util.Scanner;
/**
* 获取一个字符串在另一个字符串中出现的次数
* @author 淡定
* @date 2022-05-10 9:37
*/
public class CountProblem1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串");
//nextLine()读取到回车停止 ,在读取输入后将光标放在下一行。
String s = sc.nextLine();
Scanner sc2 = new Scanner(System.in);
System.out.println("输入字符串");
String sub = sc2.nextLine();
// int filter = filter(s,sub);
// int getCount = getCount(s,sub);
int count = count(s,sub);
// System.out.println(sub + "在字符串中出现了" + filter +"次");
System.out.println(sub + "在字符串中出现了" + count +"次");
}
/**
* 方式一 String里面的indexOf方法.
* 通过判断返回的值不等于-1开始循环.
* indexOf是返回 指定字符串 在 原来的字符串 出现 第一次的位置索引.
* 然后下次循环就从这一次的下一次开始循环.每次得到索引值时 计数器 加一
* @param mainStr
* @param substr
* @return
*/
public static int getCount(String mainStr, String substr) {
int mainLength = mainStr.length();
int subLength = substr.length();
int count = 0;
int index = 0;
if (mainLength >= subLength) {
// 方式一
while ((index = mainStr.indexOf(substr)) != -1) {
count++;
mainStr = mainStr.substring(index + substr.length());
}
// 方式二
while ((index = mainStr.indexOf(substr, index)) != -1) {
count++;
index += subLength;
}
return count;
} else {
return 0;
}
}
/**
* 方式二 替换为空 (newString-oldString)/sub=次数
* 获取sub 在s中出现的次数
* @param s
* @param sub
* @return
*/
public static int filter(String s,String sub){
int old_length = s.length();
String replace = "";
if(s.contains(sub)){
replace = s.replace(sub,"");
}
int new_length= replace.length();
int count=(old_length-new_length)/(sub.length());
return count;
}
/**
* 方式三
* 类似方式二
* indexOf是返回 指定字符串 在 原来的字符串 出现 第一次的位置索引 返回值-1表示不存在该字符.
* 然后下次循环就从这一次的下一次开始循环.每次得到索引值时 计数器 加一
* @param s
* @param sub
*/
public static int count(String s,String sub){
int count = 0;
while(true){
int i = s.indexOf(sub);
if(i == -1){
break;
}else{
count++;
s = s.substring(i+sub.length());
}
}
return count;
}
}
获取一个字符串在另一个字符串中出现的次数
于 2022-05-19 14:01:28 首次发布
本文介绍了一种Java实现的方法,通过`CountProblem1`类展示了如何使用indexOf和substring等方法计算一个字符串在另一个字符串中出现的次数,包括两种方式:一种是基于indexOf逐次查找,另一种是利用replace操作计算替换次数。
摘要由CSDN通过智能技术生成