0
点赞
收藏
分享

微信扫一扫

android 获取某个字符出现的次数


下面是找出"|"出现的次数:

String str = "[gift]GG|www.url|30|1";
String key = "|";  //找出"|"出现的次数
int count = getKeyTime(str,key);
Log.e("|出现的次数为", count+"");
 public static int getKeyTime(String str, String key) {
      int index = 0; //定义变量。记录每一次找到的key的位置。
      int count = 0; //定义变量,记录出现的次数。

      //定义循环。只要索引到的位置不是-1,继续查找。
      while((index = str.indexOf(key,index))!=-1){
           //每循环一次,就要明确下一次查找的起始位置。
           index = index + key.length();
           //每查找一次,count自增。
           count++;
       }
     return count;
 }

 


举报

相关推荐

0 条评论