计算字串出现关键字次数和所在位置

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class CalStringOccurrence {
	
	
	public static int calOccurences(final String input,final String searchWord){
		int occurrences = 0,index = 0;
		if (input == null || searchWord == null)
			return occurrences;
		while((index = input.indexOf(searchWord,index))>=0){
			occurrences++;
			index+=searchWord.length();
		}
		return occurrences;
	}
	
	public static List<Integer> calIndexes(final String input,final String searchWord){
		List<Integer> indexes = null;
		if (input == null || searchWord == null)
			return null;
		indexes = new ArrayList<Integer>();
		int index = 0;
		while((index = input.indexOf(searchWord,index))>=0){
			indexes.add(new Integer(index));
			index+=searchWord.length();
		}
		return indexes;
	}
	
	private static boolean test_calIndexes(final String input,final String word){
		List<Integer> indexes = CalStringOccurrence.calIndexes(input,word);
		if (indexes == null)
		   return true;
		for(Iterator<Integer> it = indexes.iterator();it.hasNext();){
			int index = it.next().intValue();
			if(!input.substring(index, index+word.length()).equals(word)){
				return false;
			}
		}
		return true;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String input = "California’s Congressional delegation, " +
				"the largest and most influential in the nation, is undergoing a major upheaval," +
				" the result of reapportionment and retirements, threatening the state’s influence " +
				"in Washington next year and forcing members to scramble to withstand what is emerging " +
				"as a generational wave";
		String key = "the";
		System.out.println(CalStringOccurrence.calOccurences(input,key));
		System.out.println(CalStringOccurrence.calIndexes(input,key));
		System.out.println(CalStringOccurrence.test_calIndexes(input,key));
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值