数据结构——串的基本操作及模式匹配

一.统计一个串中字符的出现次数

二.方法与步骤

利用String的indexof(str,fromindex)方法,循环遍历加一个计数器统计次数。

三.实验原始纪录

public class CountTimes{

public static void main(String[] args)

{

String str= "各个国家有各个国家的国歌";

int times = searchstr("国", str); //返回3

System.out.println(times);

}

public static int searchstr(String key, String str)

{

int index = 0;//每次的搜索到的下标

int count = 0;//计数器

while (( index=str.indexOf(key, index)) != -1)

{

index = index + key.length();

count++;

}

return count;

}

}

五.结果

“国”在“各个国家有各个国家的国歌”中出现了三次

猜你喜欢

转载自blog.csdn.net/weixin_45823684/article/details/128536663