unicorn的java课堂笔记(9)下

作者在 2006-12-17 21:42:00 发布以下内容

6.字符串与字符,字节数组
1)字符串和字符数组
a)用字符数组创建字符串对象

String (char[]) //该构造方法用指定的字符数组构造一个字符串对象
String (char[],int offset,int length) //用指定的字符数组的一部分,即从起始位置offset开始取length个字符构造字符串对象

如前面的例子:

char a[]={'b','o','y'};
String s=new=new String(a);

b)将字符串中的字符复制到字符数组
public void getChars(int start,int end,char c[],int offset) //字符串调用此方法将当前的字符串中的一部分字符复制到数组c中,将字符串中从start到end-1位置上的字符复制到数组c中,并从数组c中的offset处开始存放这些字符,需要注意的是,必须保证数促c能容纳下要复制的字符.

public char[] toCharArray() 字符串对象调用该方法可以初始化一个字符数组,该数组的长度与字符串的长度相等,并将字符串对象的全部字符复制到该数组中.

体会下面俩个例子:

程序代码:


class E
{  public static void main(String args[])
   {  char c[],d[],e[];
      String s="巴西足球队击败德国足球队";
      c=new char[2];
      s.getChars(5,7,c,0);
      System.out.println(c); //输出击败
      d=new char[s.length()];
      s.getChars(7,12,d,0);
      s.getChars(5,7,d,5);
      s.getChars(0,5,d,7);
      System.out.println(d);//d[]中保存的是德国足球队击败巴西足球队
      e=new char[s.length()];
      e=s.toCharArray()
      System.out.println(e);//e[]中保存的s的内容即"巴西足球队击败德国足球队"
      
   }
}


程序代码:


class E
{  public static void main(String args[])
   {  String s="编程论坛";
      char a[]=s.toCharArray();//把字符串转成字符数组
      for(int i=0;i<a.length;i++)
        {  a=(char)(a^'t');//把每个字符都处理下
        }
String secret=new String(a);
System.out.println("密文:"+secret);
      for(int i=0;i<a.length;i++)
       {  a=(char)(a^'t');
       }
String code=new String(a);  
  System.out.println("原文:"+code);
   }
}


2)字符串和字节数组
和字符数组的形容类似
a)用字节创建字符串对象
String (byte [])

String (byte[],int offset,int length)

b)将字符串转换为字节数组
public byte[] getBytes()

例如:

程序代码:


public class E
{  public static void main(String args[])
   {  byte d[]="你我他".getBytes();          
      System.out.println("数组d的长度是(一个汉字占两个字节):"+d.length);//输出"数组d的长度是(一个汉字占两个字节):6"
      String s=new String(d,0,2);
      System.out.println(s);//输出"你"
   }
}

7.StringBuffer类

前面学习了String字符串对象,Str

转帖&&连载 | 阅读 971 次
文章评论,共0条
游客请输入验证码