统计一段长字符串中某字符串的出现次数

  • 截取字符串统计字符串出现次数
  • 通过替换字符串,统计字符串出现次数
  • 通过正则表达式,统计字符串出现次数

 

package constxiong.interview;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 统计一段长字符串中某字符串的出现次数
 * @author ConstXiong
 * @date 2019-11-13 11:01:22
 */
public class TestCountWordTimesInText {

	public static void main(String[] args) {
		String text = "统计一CX段长CX字符串中某字符串的出C现X次cx数";
		String word = "CX";
		System.out.println(countWordTimesByCutString(text, word));
		System.out.println(countWordTimesByReplace(text, word));
		System.out.println(countWordTimesByRegex(text, word));//正则匹配,需要注通配符的使用对结果的影响
	}

	/**
	 * 截取字符串统计字符串出现次数
	 * @param text
	 * @param word
	 * @return
	 */
	public static int countWordTimesByCutString(String text, String word) {
		int times = 0;
		if (!isEmpty(text) && !isEmpty(word)) {
			String subText = text;
			int index = -1;
			int wordLength = word.length();
			while (subText.length() >= wordLength && (index = subText.indexOf(word)) > -1) {
				subText = subText.substring(index + wordLength);
				times++;
			}
		}
		return times;
	}
	
	/**
	 * 通过替换字符串,统计字符串出现次数
	 * @param text
	 * @param word
	 * @return
	 */
	public static int countWordTimesByReplace(String text, String word) {
		int times = 0;
		if (!isEmpty(text) && !isEmpty(word)) {
			times = (text.length() - text.replace(word, "").length()) / word.length();
		}
		return times;
	}
	
	/**
	 * 通过正则表达式,统计字符串出现次数
	 * @param text
	 * @param word
	 * @return
	 */
	public static int countWordTimesByRegex(String text, String word) {
		int times = 0;
		if (!isEmpty(text) && !isEmpty(word)) {
			Pattern p = Pattern.compile(word);
			Matcher m = p.matcher(text);
			while (m.find()) {
				times++;
			}
		}
		return times;
	}
	
	/**
	 * 字符串是否为空
	 * @param str
	 * @return
	 */
	private static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}
	
}

 


【Java面试题与答案】整理推荐

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值