看這段英文的變化,輸入的值的是綠色圈出的部分,第一次處理后的結果是橙色圈出的部分,第三次處理的結果是紅色圈出的部分,第一次處理,先是對句話進行了切分,是按照單詞之間的空格進行切分,將一整句話切分成多個單詞,然后對這些單詞的進行移位,每次都將第一個單詞放在末尾從而組成新的句子,這樣經過第一次處理之后,HELLO WORLD 這句話就變成了兩句話HELLO WORLD 和WORLD HELLO。接下來進行第二步處理,對這幾句話按照首字母進行排序,從而得到最終的結果。
2、管道過濾器風格 實現代碼如下 第一版:(具體的思路看代碼的注釋)
package com.bren.cn;import java.io.IOException;import java.util.ArrayList;import java.util.StringTokenizer;import java.io.PipedInputStream;import java.io.PipedOutputStream;/*** * @author huihui 基于管道過濾器模式,這是第一版*/publicclassmypip{/*** 第一步我應該有一個管道 我需要導入java的管道流的包* @throws IOException */publicstaticvoidmain(String[] args)throws IOException {/*** 輸入管道流*/ PipedInputStream inPip;PipedOutputStream outPip;/*** 管道相連*/inPip=newPipedInputStream();outPip =newPipedOutputStream();try{inPip.connect(outPip);}catch(IOException e){// TODO Auto-generated catch blocke.printStackTrace();}/*** 第二步我需要向管道中讀入數據"Hello Yolo I am Boss"*/byte[] out =newbyte[1024];byte[] in =newbyte[1024];String s =newString("hello yolo i am boss");//這里我可以按行讀取一個外部的文件outPip.write(s.getBytes());//向管道中寫入數據 outPip.close();/*** 第三步我需要使用過濾器對管道中的數據進行切分* 1、先拿取管道中的數據* 2、進行切分移位之后再放回管道中*/int len =0;len=inPip.read(in);//從管道中拿取數據s =newString(in,0, len);//得到字符串sinPip.close();//1、切分StringTokenizer tokener =newStringTokenizer(s," ");//2、進行移位操作String token =newString();int index; ArrayList<String> tokens =newArrayList<String>();int count = tokener.countTokens();for(int j =0; j < count; j++){//將一行解析,并且將解析的word加入ArrayList中 token = tokener.nextToken(); tokens.add(token);}ArrayList<String> kwicList =newArrayList<String>();//對ArrayList中的字進行循環移位,得出最后結果 for(int i =0; i < count; i++){ index=i; StringBuffer linebuffer =newStringBuffer();for(int j =0; j < count; j++){if(index >= count) index =0; linebuffer.append ( tokens.get(index)); linebuffer.append (" "); index++;}String line = linebuffer.toString(); kwicList.add(line);}/*** 3、移位之后再次寫入到管道中,進行下一個過濾器*/PipedInputStream inPip2;PipedOutputStream outPip2;/*** 管道相連*/inPip2=newPipedInputStream();outPip2 =newPipedOutputStream();try{inPip2.connect(outPip2);}catch(IOException e){// TODO Auto-generated catch blocke.printStackTrace();}String s1="";for(int count1 =0; count1 < kwicList.size(); count1++){s1 =s1+kwicList.get (count1)+"\n";}System.out.println(s1);outPip2.write(s1.getBytes());outPip2.close();/*** 4、再次讀取管道中的數據、進行首字母排序處理,按照換行符讀取形成字符串數組*/System.out.println("輸出in"+in[0]);len = inPip2.read(in);s =newString(in,0, len);String []ss= s.split("\n").clone();ArrayList<String> list=newArrayList<String>();for(String n:ss){System.out.println("輸出"+n);}list.sort(null);for(int coun=0;coun<list.size();coun++){System.out.println(list.get(coun));}}}