下面的代码用index();方法来获取一个字符串在另一个字符串中出现的次数。还有别的更好的方法吗- package com.Thread;
- public class StringTest3 {
- public static void sop(String str){
- System.out.println(str);
- }
- public static void main(String[] args) {
-
- String s = "abkkcdefkkghykk";
-
- sop("count="+getSubCount(s,"kk"));
- }
-
- public static int getSubCount(String str,String key){
- int count = 0;
- int index = 0;
-
- while((index = str.indexOf(key))!=-1){
- sop("str="+str);
- str = str.substring(index+key.length());
-
- count++;
-
- }
- return count;
- }
- }
复制代码
|