我是靠谱客的博主 危机鞋子,这篇文章主要介绍java小练习--获取abc字符串在整个字符串中出现的次数,现在分享给大家,希望可以做个参考。

在下面一行字符串中获取abc字符串在整个字符串中出现的次数。
"wabcerabctyabcuiabcabcqq"

思路:使用indexOf和substring();

源码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public static void main(String[] args) { String s1 = "abcwabcerabctyabcuiabcabc"; String s2 = "abc"; int count = getCount(s1,s2); int count2 = getCount2(s1,s2); System.out.println("count = "+count); System.out.println("count2 = "+count2); } /*第一种方法 获取abc字符串在整个字符串中出现的次数。 "wabcerabctyabcuiabcabcqq" */ public static int getCount(String str,String sub) { int index = 0; int count = 0; while((index = str.indexOf(sub,index))!=-1) { index = index + sub.length(); count++; } return count; } /*第二种方法*/ public static int getCount2(String str,String sub) { int index = 0; int count = 0; while((index=str.indexOf(sub))!=-1) { str = str.substring(index+sub.length()); count++; } return count; } }


 

最后

以上就是危机鞋子最近收集整理的关于java小练习--获取abc字符串在整个字符串中出现的次数的全部内容,更多相关java小练习--获取abc字符串在整个字符串中出现内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(85)

评论列表共有 0 条评论

立即
投稿
返回
顶部