package com.bjpowernode.demo01;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
//String构造方法,
public class Test01 {
public static void main(String[] args) throws UnsupportedEncodingException {
//1) 直接赋值字符串字面量
String s1 = "hello";
//2) 无参构造
String s2 = new String(); //长度为0的字符串, 相当于"",空串
//new运算符在堆区中创建一个对象 , 把该对象的引用(地址)赋值给s2变量
System.out.println( s2.length() );
//3)根据字节数组创建String对象
byte[]bytes = {65,66,67,97,98,99,100};
//把bytes字节数组中的内容, 根据当前默认的编码格式(utf-8)转换为字符串
String s3 = new String(bytes);
System.out.println( s3 ); //ABCabcd
//根据字节数组中的部分字节创建String对象, 把byte字节数组中从2开始的4个字节转换为字符串
s3 = new String(bytes , 2 , 4);
System.out.println( s3 ); //Cabc
//把字节 数组中的字节转换为字符串时,可以指定编码格式
bytes = "hello,动力节点".getBytes(); //字符串的getBytes()可以把字符串转换为默认编码下的字节数组
System.out.println( Arrays.toString(bytes));
//[104, 101, 108, 108, 111, 44, -27, -118, -88, -27, -118, -101, -24, -118, -126, -25, -126, -71]
//utf-8编码中, 一个英文字符占1字节, 一个汉字占3个字节
s3 = new String(bytes, "UTF-8"); //使用utf-8编码把字节数组转换为字符串
System.out.println( s3 );
s3 = new String(bytes, "GBK"); //使用GBK编码把字节数组转换为字符串
System.out.println( s3 ); //hello,锷ㄥ姏鑺傜偣
//在GBK编码中,一个英文字符占1字节,一个汉字占2个字节
//4) 根据字符数组创建字符串对象
char[]contents = {'A','*','汉','妃','菲','6'};
String s4 = new String(contents);
System.out.println( s4 ); //A*汉妃菲6
s4 = new String(contents, 2, 3); //从2开始的3个字符转换为字符串
System.out.println( s4 );
//5) 根据已有的String对象创建新的字符串
String s5 = new String(s4);
System.out.println( s5 );
System.out.println( s4 == s5 ); //false
}
}
java基础回顾之String的构造方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.