统计一个字符串在另一个字符串中出现次数(java)(2006-12-22 15:16:00)
//这是一个用java语言编写的统计字符串出现次数的代码
/*
*统计字符串出现的次数
*/
public class TwoTest{
public static void main(String [] args){
String s="lsdd";
String y="iloveyouwhyyoulovemelove";
System.out.println(new TwoTest().countNumber(s,y));
}
public int countNumber(String s,String y){ //统计方法
int count=0;
String [] k=y.split(s); //将字符串通过s断开返回数组k
if(y.lastIndexOf(s)==(y.length()-s.length())) //如果y最后一个包含s的索引等于y的长度-要的长度,那么出现的次数就等于k的长度
count=k.length;
else
count=k.length-1;//否则k长度-1,因为s不是单字符是多个
if(count==0)
System.out.println ("字符串\""+s+"\"在字符串\""+y+"\"没有出现过");
else
return count;
return -1;
}
}
文章摘自http://blog.pfan.cn/bluedance
//这是一个用java语言编写的统计字符串出现次数的代码
/*
*统计字符串出现的次数
*/
public class TwoTest{
public static void main(String [] args){
String s="lsdd";
String y="iloveyouwhyyoulovemelove";
System.out.println(new TwoTest().countNumber(s,y));
}
public int countNumber(String s,String y){ //统计方法
int count=0;
String [] k=y.split(s); //将字符串通过s断开返回数组k
if(y.lastIndexOf(s)==(y.length()-s.length())) //如果y最后一个包含s的索引等于y的长度-要的长度,那么出现的次数就等于k的长度
count=k.length;
else
count=k.length-1;//否则k长度-1,因为s不是单字符是多个
if(count==0)
System.out.println ("字符串\""+s+"\"在字符串\""+y+"\"没有出现过");
else
return count;
return -1;
}
}
文章摘自http://blog.pfan.cn/bluedance