1. 程式人生 > >編寫程式實現:輸入一篇文章,統計該文章中“指定字串”的出現次數

編寫程式實現:輸入一篇文章,統計該文章中“指定字串”的出現次數

/*
(2)編寫程式實現:輸入一篇文章,統計該文章中“中國”的出現次數
public int count(String article){

}

/
//第一種
import java.util.Scanner;
class CountString{
public int count(String article,String hunt){
//String str =article;
//判斷是否有你要找的字;
if(article.indexOf(hunt)==(-1)){
return -1;
}else{
int i=0;
int s = article.indexOf(hunt);
do{
article = article.substring(s+hunt.length());
s = article.indexOf(hunt);
i++;
}while(s!=(-1));
return i;
}
}
}
/


//第二種
class CountString{
public int count(String article,String hunt){
//判斷是否有你要找的字;
String[]array=article.split(“hunt”);
if(article.substring(article.length()-2).equals(“hunt”)){
return array.length;
}
return array.length-1;
}
}
*/
public class TestCountString{
public static void main(String []args){
Scanner sc = new Scanner(
System.in
);
System.out.println(“請輸入一段文章”);
String str = sc.next();
System.out.println(“請輸入文章中要書的關鍵字”);
String hunt =sc.next();
CountString cs = new CountString();
int a = cs.count(str,hunt);
if(a==(-1)){
System.out.println(“文章中沒要搜尋的關鍵字”);
}else{
System.out.println(“文章中要搜尋的關鍵字的個數是:”+a);
}
}
}