a- package demo.collection;
- public class CountSubstringDemo {
- /**
- * 2、一个子串"nba"在整串中出现的次数 "nbaernbatynbauinbaopnba"
- */
- public static void main(String[] args) {
- String src = "nbaernbatynbauinbaopnba";
- String key = "nba";
- countSubstring(src, key);
- }
- private static void countSubstring(String src, String key) {
- int offset = 0;
- int count = 0;
- while((offset = src.indexOf(key,offset))!=-1){
- System.out.println("offset = "+offset);
- offset++;
- count++;
- }
- System.out.println(count);
- }
- }
复制代码
|
|