日期:2014-05-20 浏览次数:20744 次
/** * 计算字符串中子串出现的次数。 * 例如字符串abdeacdsdfsdfacddfsfdsacd中,字符串acd出现了3次 */ public class $2_SubStringNumber { public static void main(String[] args) { //测试A System.out.println("测试A,0"); new $2_SubStringNumber().subStringNubmer("abc", "test"); System.out.println("测试A,1"); new $2_SubStringNumber().subStringNubmer("abc", "abc"); System.out.println("测试c,2"); new $2_SubStringNumber().subStringNubmer("abcabc", "abc"); System.out.println("测试d,2"); new $2_SubStringNumber().subStringNubmer("abcabc", "ab"); } public int subStringNubmer(String source,String target){ int count=0;//标记字串出现的个数 int begin=0;//标记搜索的开始位 if(source.length()<target.length())return 0; if(source.equals(target))return 1; while(begin<=source.length()-target.length()){ if(source.substring(begin, begin+target.length()).equals(target)){ count++; } begin+=target.length(); } return count; } }
public static void main(String[] args) { int a; //测试A a = new $2_SubStringNumber().subStringNubmer("abc", "test"); System.out.println("测试A,0. 结果=" + a); a = new $2_SubStringNumber().subStringNubmer("abc", "abc"); System.out.println("测试A,1. 结果=" + a); a = new $2_SubStringNumber().subStringNubmer("abcabc", "abc"); System.out.println("测试c,2. 结果=" + a); a= new $2_SubStringNumber().subStringNubmer("abcabc", "ab"); System.out.println("测试d,2. 结果=" + a); }