天天看點

String類常用方法之charAt()、codePointAt()示例

1、chatat()——提取指定字元串

2、codepointat()——提取索引字元代碼點

java代碼

/**  

 * 作者:陽光的味道  

 * 功能:   string類常用方法之charat()、codepointat()  

 * 日期:2010/11/07  

 * */  

public class stringdemo {   

    public static void main(string[] args) {   

        string str1 = "abcdefg";   

        char ch1 = str1.charat(0);   

        system.out.println("使用charat()方法" +   

                "從字元串中提取字元,結果是:" + ch1);   

        int codepoint = 0;   

        for(int i = 0 ; i < 8 ; i ++){   

            try{   

                codepoint = str1.codepointat(i);   

            }catch(stringindexoutofboundsexception e1){   

                system.out.println("codepointay()所調用的索引值" + i +    

                        "已經超出所要查詢的字元串的長度!");   

            }finally{   

                try{   

                    system.out.println(str1.charat(i)    

                            + "的unicode碼為" + ":" + codepoint);   

                }catch(stringindexoutofboundsexception e2){   

                    system.out.println("charat()所調用的索引值" + i +    

                            "已經超出所要查詢的字元串的長度!");   

                }   

            }   

        }   

    }   

}   

/*out:  

 使用charat()方法從字元串中提取字元,結果是:a  

a的unicode碼為:97  

b的unicode碼為:98  

c的unicode碼為:99  

d的unicode碼為:100  

e的unicode碼為:101  

f的unicode碼為:102  

g的unicode碼為:103  

codepointay()所調用的索引值7已經超出所要查詢的字元串的長度!  

charat()所調用的索引值7已經超出所要查詢的字元串的長度!*/