1. 程式人生 > >統計一段話中,單詞的個數

統計一段話中,單詞的個數

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternAndMatcherDemo {
public static void main(String[] args) {

    int  count  = 0;
    String str = " a sense we've come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable Rights" of "Life";
    Pattern p = Pattern.compile("\\b[a-zA-Z]{1,}\\b");// 統計單詞個數 \\b為單詞邊界

    Matcher matcher = p.matcher(str);
    while(matcher.find()) {
        count++;
        System.out.println(matcher.group());
    }
    System.out.println(count);

}

}