对象的字符串表示,以及字符串与字符,字节数组

mac2026-08-09  3

通过字符数组或者字节数组创建字符串对象 String s=new String(char a[]) String s=new String(char a[],int offset,int length) String s=new String(byte a[]) String s=new String(byte a[],int offset,int length)

package train; public class Demo{ public static void main(String[] args) { Demo1 s=new Demo1("hello world!"); System.out.println(s); } } class Demo1 { String str; Demo1(String s) { str=s; } public String toString() { String oldMethod=super.toString(); return "调用原toString方法得出的结果:"+oldMethod+"\n调用重写的toString方法得出的结果:"+str; } }

运行结果如下: 总结:对象调用toString方法可以得到它的字符串表示 一般形式如下: 类名@对象的引用的字符串表示 二.

package train; public class Demo<c> { public static void main(String[] args) { char[] a, b; String s = new String("字符串与字符数组"); a = new char[4]; // public void getChars(int start,int end,char[],int offer)将当前字符串的一部分字符复制到指定的数组中 s.getChars(4, 8, a, 0); // public char[] toCharArray()返回一个字符数组,数组长度与字符串长度相同 b = new char[8]; b = s.toCharArray(); System.out.println(a); System.out.println(b); // public byte[] getBytes(String charsetname)将当前字符串转换为一个字节数组,其中charsetname为字符编码方式 byte c[] = new byte[16]; byte c1[]=new byte[32]; String s1 = "字符串与字节数组"; try{c = s1.getBytes("GB2312");}//采用GB2312编码,一个汉字占2个字节 catch(Exception e){} try{ c1=s1.getBytes("utf-8");}//采用utf-8编码,一个汉字占3个字节 catch(Exception e){} System.out.println(c.length); System.out.println(c1.length); } }

运行结果如下:

最新回复(0)