Java210 字元搜尋器


package java實用級;

import java.util.Scanner;
import java.io.InputStreamReader;

public class J210 {

    public J210() {
        // TODO Auto-generated constructor stub
    }
   public static void main(String args[]){

       Scanner sc = new Scanner(System.in);
       
       System.out.println("請輸入字串");
       String str = sc.nextLine();
       System.out.println("請輸入要搜尋的字元或字串");
       String ctr = sc.nextLine();

       int site=str.indexOf(ctr);
       int len=ctr.length();
       int count=0;

       if(site==-1){
           System.out.println("顯示要搜尋的字元不在字串中");}
       else{
           System.out.println("第幾個位置找到了");
           do{
         
               System.out.println(site+1-(count*(len-1)));
               site=str.indexOf(ctr,site+1);
               count++;
           }while(site!=-1);
       }       
             
   }

}

Java209 文字編碼的轉換

package java實用級;

public class J209 {

    public J209() {
        // TODO Auto-generated constructor stub
    }
    public static void main(String[] args) {
        String str = "JAVA程式"; 
       
        //將字串strUnicode碼以16進位表示,並轉成字串。
        String str16=toHexString(str);
        System.out.println(str16);
       
       
        //將字串str轉成Big5
        String strb = unicodeToBig5(str);
       
        //將字串strBig5碼以16進位表示,並轉成字串。
        str16 = toHexString(strb);
        System.out.println(str16);
       
        //Big5碼表示的字串strBig5再轉回Unicode碼,得到原字串。
        String stru = big5ToUnicode(strb);
        System.out.println(stru);
    }

     
    // 方法toHexString接受一個字串當參數,取出字串中每一個字元的16進位碼
    // (4位數),再將這些16進位碼串成字串後傳回,每個碼之間用一空白分隔。
    public static String toHexString(String str) {
        // 請在此寫出本方法的程式碼
        String strResult = "";
        String tmp;
        char c;
        for(int i=0; i<str.length(); i++)
            {
                c=str.charAt(i);
                tmp="0000"+Integer.toHexString(c);
                strResult+=tmp.substring((tmp.length()-4))+" ";
            }
        return strResult;
    }  
       
    // 方法unicodeToBig5接受一個以Unicode表示的字串,
    // 將其轉成以Big5表示的字串後傳回。
    public static String unicodeToBig5(String str) {
    // 請在此寫出本方法的程式碼
        String strResult = "";
        try{
            strResult=new String(str.getBytes("Big5"),"ISO8859_1");
        }
        catch(Exception e){}   
        return strResult;
    }  

    // 方法big5ToUnicode接受一個以Big5表示的字串,
    // 將其轉成以Unicode表示的字串後傳回。
    public static String big5ToUnicode(String str) {
    // 請在此寫出本方法的程式碼
        String strResult = "";
        try{
            strResult=new String(str.getBytes("ISO8859_1"),"Big5");
        }
        catch(Exception e){}   
        return strResult;  
    }
}