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的内容即"巴西足球队击败德国足球队"
}
}
[code]
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);
}
}
[/code