编写一个类,该类的功能是可以根据给定的字符串(字符串的内容可以是中文,也可以是英文,字符串中单词之间可以有空格,也可以没有空格)和子串,计算出字符串中包含多少个子串。(要求:使用String类的方法。)
程序可以使用下面的框架:
import java.util.Scanner;
class CountSubString
{
//【变量声明】
//方法实现
void countSubString(String s, String substring) //s代表整个字符串,substring代表子串
{
//【代码】
}
}
public class CountString
{
public static void main(String args[])
{
Scanner reader=new Scanner(System.in);
System.out.println("请输入字符串:");
String s=reader.nextLine();
System.out.println("请输入你要检索的子串:");
String substring=reader.nextLine();
CountSubString a=new CountSubString();
a.countSubString(s, substring);
}
}
例如,可以输入字符串“I like apple. The apple is decilious. Do you like apple?”和子串“apple”,程序的运行结果应该是检索到3个apple。
再例如,可以输入字符串“Ilikeapple.Theappleisdecilious.Doyoulikeapple?”和子串“apple”,程序的运行结果应该是检索到3个apple。
再例如,可以输入字符串"我喜欢苹果。苹果很美味。你喜欢苹果吗?"和子串"苹果",程序的运行结果应该是检索到3个“苹果”。
看看这个代码,很简单的, 你这个应该是初学者,你可以多思考下,你传入的字符长度是多少,然后再查看你要搜索的字符长度多少,然后一点一点的比对
void countSubString改成int返回类型,即:
public int countSubString(String str, String subStr) {
int count = 0;
int index = -1;
while ((index = str.indexOf(subStr, index)) > -1) {
++index;
++count;
}
return count;
}
这个不是查找问题,应该是分词问题
先把整个字符串分词,看有多少个子串
然后才能统计子串,分词是一个复杂问题,英文由于有空格比较分,中文使用最长语义匹配获取分词
直接用子串作为分隔符, 拆出来多少段再减一就是有多少个子串.
代码:
public int countSubString(String str, String subStr) {
return str.split(subStr).length - 1;
}
这个很容易啊,虽然我不会但我一看就知道很容易