Java编程思想第四版13章 个人练习

 

练习12:(5)修改groups.java,找出所有不以大写字母开头的单词,不重复的计算其个数。

 

package thinkjava13;

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

public class A05Groups  {
	public static final String POEM="Twas briling,and the slithy toves\n"+
	"Did gyre and gimble in the wabe,"+
	"Did gyre and gimble in the wabe,\n"+
	"All mimsy were the borogoves ,\n"+
	"And the mome raths outgrabe.\n\n"+
	"Beware the Jabberwock. my son,\n"+
	"The jaws that bite ,the claww that catch. \n"+
	"Beware the Jubjub bird,and shun\n"+
	"The frumious Bandersnath.";
	public static void main(String args[]){
		//(?m):打开多行模式
		Matcher m=Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM);
		while(m.find()){
			for(int i=0;i<=m.groupCount();i++){
				System.out.print(i+"->【"+m.group(i)+"】\t");
			}
			System.out.println();
		}
		System.out.println("-----------------------------------");
		Matcher m1=Pattern.compile("(?m)\\W([a-z]+)\\W").matcher(POEM);
		Set<String> set=new HashSet<String>();
		int count=0;
		int total=0;
		while(m1.find()){
			String word=m1.group(1);
			if(set.contains(word)){
				total++;
			}else{
				count++;
				set.add(word);
			}
			m1.region(m1.end()-1, POEM.length());
		}
		System.out.println("总共匹配非重复个数:"+count+"\t重复:"+total);
		System.out.println(set);
	}
	/**
	 * 输出结果如下:
	 * 0->【the slithy toves】	1->【the】	2->【slithy toves】	3->【slithy】	4->【toves】	
0->【in the wabe,】	1->【in】	2->【the wabe,】	3->【the】	4->【wabe,】	
0->【the borogoves ,】	1->【the】	2->【borogoves ,】	3->【borogoves】	4->【,】	
0->【mome raths outgrabe.】	1->【mome】	2->【raths outgrabe.】	3->【raths】	4->【outgrabe.】	
0->【Jabberwock. my son,】	1->【Jabberwock.】	2->【my son,】	3->【my】	4->【son,】	
0->【Jubjub bird,and shun】	1->【Jubjub】	2->【bird,and shun】	3->【bird,and】	4->【shun】	
0->【The frumious Bandersnath.】	1->【The】	2->【frumious Bandersnath.】	3->【frumious】	4->【Bandersnath.】	
-----------------------------------
总共匹配非重复个数:25	重复:15
[briling, catch, jaws, shun, raths, were, borogoves, claww, mome, frumious, son, the, in, my, wabe, gimble, and, bird, that, bite, slithy, mimsy, outgrabe, gyre, toves]

	 */
}

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值