码迷,mamicode.com
首页 > 其他好文 > 详细

统计某字符串在另一个字符串中出现的次数

时间:2014-11-13 14:32:17      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   sp   for   div   log   bs   

 1 /**
 2  * 统计某字符串在另一个字符串中出现的次数
 3  *
 4  *
 5  */
 6 public class CountHit {
 7     public static void main(String[] args) {
 8         String a = "123456abcdde6abcbcb";
 9         String b = "6abc";
10         System.out.println(new CountHit().hit(a, b));
11     }
12  
13     /**
14      *
15      * @param a
16      *            被匹配的长字符串
17      * @param b
18      *            匹配的短字符串
19      * @return 匹配次数
20      */
21     public int hit(String a, String b) {
22         if (a.length() < b.length()) {
23             return 0;
24         }
25         char[] a_t = a.toCharArray();
26         char[] b_t = b.toCharArray();
27         int count = 0, temp = 0, j = 0;
28  
29         for (int i = 0; i < a_t.length; i++) {
30             // 保证一个连续的字符串 b 跟 a中某段相匹配
31             if (a_t[i] == b_t[j] && j < b_t.length) {
32                 temp++;
33                 j++;
34                 // 此时连续的字符串 b 跟 已跟 a 中某段相匹配
35                 if (temp == b_t.length) {
36                     count++;
37                     temp = 0;
38                     j = 0;
39                 }
40             }
41             // 只要有一个字符不匹配,temp计数从来
42             else {
43                 temp = 0;
44                 j = 0;
45             }
46         }
47  
48         return count;
49     }
50 }

 

统计某字符串在另一个字符串中出现的次数

标签:style   blog   color   ar   sp   for   div   log   bs   

原文地址:http://www.cnblogs.com/leorain/p/4094724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!