這個題目用到正則表達式,正則表達式是一種可以用於模式匹配和替換的規范.
字符串對象(String)調用matches()可以判斷當前字符串對象是否與參數regex指定的正則表達式匹配.
String上可以使用正則表達式的操作,實際上是利用了java.util.regex.Pattern與java.util.regex.Matcher的功能.當調用String的matches()方法時,實際上是調用了Pattern的靜態方法matches(),這個方法會返回boolean值,表示字符串是否符合正則表達式.
將正則表達式視為一個對象來重復使用,使用pattern的靜態方法compile()進行編譯.這個方法會返回一個Pattern的實例,這個實例代表正則表達式,之后可以重復使用Pattern實例的matcher()方法來返回一個Matcher的實例,代表符合正則表達式的實例.
1 import java.util.Scanner; 2 import java.util.regex.Matcher; 3 import java.util.regex.Pattern; 4 5 public class Test5_1 { 6 public static void main(String[] args){ 7 int countC=0,countW=0,countS=0; //分別表示字符,單詞和句子的個數 8 Scanner in=new Scanner(System.in); 9 System.out.print("input a english sentence:"); 10 String st=in.nextLine(); //用nextInt接收,是以回車作為分隔符.而用next接受,是以空格作為分隔符. 11 Pattern p2=Pattern.compile("[ ,.!?]"); //與[]中的任意一個字符匹配即可.分別有空格,逗號,句號,感嘆號,問號.用以統計單詞個數. 12 Matcher m2=p2.matcher(st); 13 Pattern p1=Pattern.compile("[a-zA-Z ,.!?]"); //匹配一段話中字符的個數 14 Matcher m1=p1.matcher(st); 15 Pattern p3=Pattern.compile("[.!?]"); //匹配一段話中句子的個數 16 Matcher m3=p3.matcher(st); 17 boolean result2=m2.find(); 18 while(result2){ 19 countW++; 20 result2=m2.find(); //判斷是否找到並統計個數 21 } 22 boolean result1=m1.find(); 23 while(result1){ 24 countC++; 25 result1=m1.find(); 26 } 27 boolean result3=m3.find(); 28 while(result3){ 29 countS++; 30 result3=m3.find(); 31 } 32 System.out.println("單詞個數:"+countW); 33 System.out.println("字符個數:"+countC); 34 System.out.println("句子個數:"+countS); 35 } 36 }