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

来源:互联网 发布:猛龙数据 编辑:程序博客网 时间:2024/06/05 01:58

1、chatAt()——提取指定字符串

2、codePointAt()——提取索引字符代码点

 

Java代码
  1. /**  
  2.  * 作者:阳光的味道  
  3.  * 功能:   String类常用方法之charAt()、codePointAt()  
  4.  * 日期:2010/11/07  
  5.  * */  
  6. public class StringDemo {   
  7.     public static void main(String[] args) {   
  8.         String str1 = "abcdefg";   
  9.         char ch1 = str1.charAt(0);   
  10.         System.out.println("使用charAt()方法" +   
  11.                 "从字符串中提取字符,结果是:" + ch1);   
  12.         int codePoint = 0;   
  13.         for(int i = 0 ; i < 8 ; i ++){   
  14.             try{   
  15.                 codePoint = str1.codePointAt(i);   
  16.             }catch(StringIndexOutOfBoundsException e1){   
  17.                 System.out.println("codePointAy()所调用的索引值" + i +    
  18.                         "已经超出所要查询的字符串的长度!");   
  19.             }finally{   
  20.                 try{   
  21.                     System.out.println(str1.charAt(i)    
  22.                             + "的Unicode码为" + ":" + codePoint);   
  23.                 }catch(StringIndexOutOfBoundsException e2){   
  24.                     System.out.println("charAt()所调用的索引值" + i +    
  25.                             "已经超出所要查询的字符串的长度!");   
  26.                 }   
  27.                    
  28.             }   
  29.         }   
  30.            
  31.            
  32.     }   
  33.   
  34. }   
  35. /*out:  
  36.  使用charAt()方法从字符串中提取字符,结果是:a  
  37. a的Unicode码为:97  
  38. b的Unicode码为:98  
  39. c的Unicode码为:99  
  40. d的Unicode码为:100  
  41. e的Unicode码为:101  
  42. f的Unicode码为:102  
  43. g的Unicode码为:103  
  44. codePointAy()所调用的索引值7已经超出所要查询的字符串的长度!  
  45. charAt()所调用的索引值7已经超出所要查询的字符串的长度!*/  
原创粉丝点击