黑马程序员技术交流社区

标题: String类 常用方法 [打印本页]

作者: 果维    时间: 2015-12-24 18:18
标题: String类 常用方法
1、字符串与字符数组之间的转换:
字符串转为字符数组:public char[] toCharArray()
字符数组转为字符串:public String(char[] value)
                  PublicString(char[] value,int offset,int count)
例:
  1. public class StringAPIDemo01{

  2.        public static void main(String args[]){

  3.               String str1 = "hello" ;                  // 定义字符串

  4.               char c[] = str1.toCharArray() ;      // 将一个字符串变为字符数组

  5.               for(int i=0;i<c.length;i++)     // 循环输出

  6.                 {System.out.print(c[i] + "、") ; }

  7.               System.out.println("") ;        // 换行

  8.               String str2 = new String(c) ;  // 将全部的字符数组变为String

  9.               String str3 = new String(c,0,3) ;   // 将部分字符数组变为String

  10.               System.out.println(str2) ;             // 输出字符串

  11.               System.out.println(str3) ;             // 输出字符串

  12.        }

  13. };
复制代码
2、字符串与字节数组之间的转换:
字符串转字节数组:public byte[] getBytes()
字符数组转字符串:public String(byte[] bytes)
                  public String(byte[] bytes,int offset,int length)

例:
  1. public class StringAPIDemo02{

  2.        public static void main(String args[]){

  3.               String str1 = "hello" ;                  // 定义字符串

  4.               byte b[] = str1.getBytes() ;    // 将字符串变为byte数组

  5.               System.out.println(new String(b)) ;      // 将全部的byte数组变为字符串

  6.               System.out.println(new String(b,1,3)) ;       // 将部分的byte数组变为字符串

  7.        }

  8. };
复制代码
3、字符串与整型数组间的转换:
  1. public class StringAPIDemo03

  2. {public static void main(String[] args)

  3.        {//字符串转为整型数组:

  4.      String s1="123456789";

  5.      int n1[]=new int[s1.length()];

  6.      for(int i=0;i<n1.length;i++)

  7.          n1[i]=Integer. parseInt(String.valueOf(s1.charAt(i)));



  8.     //整型数组转为字符串:

  9.     int n2[]={1,2,3};

  10.     String s2="";

  11.     for(int i=0;i<n2.length;i++)

  12.     s2+=Integer.toString(n2[i]);

  13.     System.out.println(s2);

  14.        }

  15. }
复制代码
4、获取给定的Index处的字符:
char charAt(int index)


例:public class StringAPIDemo04{
       public static void main(String args[]){
              String str1 = "java" ;                   // 定义String对象
              System.out.println(str1.charAt(3)) ;     // 取出字符串中第四个字符’a’
       }
};


作者: 王如是    时间: 2015-12-24 20:33
写的不错
作者: DayBreak    时间: 2015-12-24 21:18
楼上说的好。
作者: anuo    时间: 2015-12-24 21:25
嘿嘿,可以保存,楼主好人,给加精
作者: WaterTheGreat    时间: 2015-12-25 13:16
支持支持!!
作者: 一大把手    时间: 2015-12-25 16:41
很好,总结的可以啊!
作者: 337325635    时间: 2015-12-25 21:15
刚刚学到这   非常有用
作者: luyang18    时间: 2015-12-25 22:16
收藏起来,学到再回看
作者: 鳌少宝    时间: 2015-12-25 22:29
呵呵,不错加油哦
作者: ztg    时间: 2015-12-25 22:38
楼主是哪个校区的
作者: 凤凰城nash    时间: 2015-12-26 00:22
楼主好人
作者: Zrz_K    时间: 2015-12-26 23:09
这个学到了,排版不错




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2