1. 程式人生 > >java演算法知識點解析(1):字串操作

java演算法知識點解析(1):字串操作

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class main {       static int[] count=new int[4];   //定義計數器       static String[] gplt={"G","P","L","T","g","p","l","t"};       public static void main(String[] args) throws IOException {             //資料處理 //          Scanner input=new Scanner(System.in);  //Scanner可能會導致記憶體太大! //          String st=input.nextLine();   //獲取字串資訊             BufferedReader in=new BufferedReader(new InputStreamReader(System.in));             String st=in.readLine();             //資料操作             count(st);             //資料顯示             show();       } /**  * 獲取不同字元的數量計數  * @param st  */       public static void count(String st) {             //尋找G的個數             for (int i = 0; i <count.length; i++) {                   String temp=st.substring(0); //擷取整條資料                   int start=0;                   while(start!=-1){                         start=temp.indexOf(gplt[i]);                         if(start!=-1){   //有存在G                               temp=temp.substring(start+1);  //擷取後面的部分                               count[i]++;  //計數器++                         }                   }                   start=0;    //初始化查詢指標                   temp=st.substring(0); //初始化整條字串                   while(start!=-1){                         start=temp.indexOf(gplt[i+4]);                         if(start!=-1){   //有存在G                               temp=temp.substring(start+1);  //擷取後面的部分                               count[i]++;  //計數器++                         }                   }             }       } /**  * 顯示列印資料  */       public static void show() {             for (int i = 0; i < count.length; i++) {                   while(count[0]>0||count[1]>0||count[2]>0||count[3]>0){                         if(count[0]>0){                               System.out.print("G");                               count[0]--;                         }                         if(count[1]>0){                               System.out.print("P");                               count[1]--;                         }                         if(count[2]>0){                               System.out.print("L");                               count[2]--;                         }                         if(count[3]>0){                               System.out.print("T");                               count[3]--;                         }                   }             }       } }