java 温习之字符串(统计字串…

来源:互联网 发布:上班族副业知乎 编辑:程序博客网 时间:2024/06/09 05:39

package com.baidu.sep;
//统计字串在整个字符串中出现的次数

public class StringTest3 
{
public static void main(String [] args)
{
String whole ="abcnabcmabceswdbca abc dfr afc";
String son = "abc";
int ct = count1(whole, son);
System.out.println(ct);
      intct2 = count2(whole, son);
System.out.println(ct2);
}
// 这种方法是通过获得一次后截取字符串
public  static int count1(String whole,Stringson)
{
int index = 0;
int count = 0;
while((index=whole.indexOf(son))!=-1)
{
whole=whole.substring(index+son.length());
++count;
}
return count;
}
//这种方法是通过移动检索的角标(个人建议用这种,尤其是大篇幅的统计出现次数时候)
public  static int count2(String whole,Stringson)
{
int index = 0;
int count = 0;
while((index=whole.indexOf(son,index))!=-1)
{
index = index + son.length();
++count;
}
return count;
}


}

0 0
原创粉丝点击