如何在Java中找到子字符串的计数 [英] How to find the count of substring in java

查看:41
本文介绍了如何在Java中找到子字符串的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在长度为10000个字符的大字符串中查找子字符串的计数.最后,我需要删除其中的所有子字符串.例如 s = abacacac,substr = ac 出现次数= 3 ,最后的字符串是 s = ab .我的代码在下面,对于长度为10000个字符的数据而言效率不高.

I am trying to find the count of the substring in a big string of length 10000 characters. Finally I need to remove all the substring in it. example s = abacacac, substr = ac, num of occurrence = 3 and final string is s = ab. My code is below, its not efficient for data of length 10000 characters.

int count =0;
while(s.contains(substr))
{
   s= s.replaceFirst(substr,"");
   count++;    
}

推荐答案

有关:

String temp = s.replace(sub, "");
int occ = (s.length() - temp.length()) / sub.length();

只需删除所有子字符串,然后检查删除前后字符串长度的差异.将临时字符串与子字符串中的字符数相除,可以得到匹配的结果.

Just remove all the substring, then check the difference on string length before and after removal. Divide the temp string with number of characters from the substring gives you the occurrences.

这篇关于如何在Java中找到子字符串的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆