String类
1.常见构造方法
public String():空构造
public String(byte[] bytes):把字节数组转成字符串
public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
public String(char[] value):把字符数组转成字符串
public String(char[] value,int index,int count):把字符数组的一部分转成字符串
public String(String original):把字符串常量值转成字符串
String s1 = new String ( ) ;
System. out. println ( s1) ;
* * String newStr = new String ( "带有中文变量" . getBytes ( "UTF-8" ) , "ISO8859-1" ) * *
byte [ ] arr1 = { 97 , 98 , 99 } ;
String s2 = new String ( arr1) ;
System. out. println ( s2) ;
byte [ ] arr2 = { 97 , 98 , 99 , 100 , 101 , 102 } ;
String s3 = new String ( arr2, 2 , 3 ) ;
System. out. println ( s3) ;
char [ ] arr3 = { 'a' , 'b' , 'c' , 'd' , 'e' } ;
String s4 = new String ( arr3) ;
System. out. println ( s4) ;
String s5 = new String ( arr3, 1 , 3 ) ;
System. out. println ( s5) ;
String s6 = new String ( "java" ) ;
System. out. println ( s6) ;
2.String类的常见面试题
@Test
public void test3 ( ) throws Exception {
String str = "abc" ;
str = "def" ;
System. out. println ( str) ;
}
@Test
public void test5 ( ) throws Exception {
byte b = 3 + 4 ;
String s1 = "a" + "b" + "c" ;
String s2 = "abc" ;
System. out. println ( s1 == s2) ;
System. out. println ( s1. equals ( s2) ) ;
}
@Test
public void test6 ( ) throws Exception {
String s1 = new String ( "abc" ) ;
String s2 = "abc" ;
System. out. println ( s1 == s2) ;
System. out. println ( s1. equals ( s2) ) ;
}
@Test
public void test7 ( ) throws Exception {
String s1 = new String ( "abc" ) ;
System. out. println ( s1) ;
}
@Test
public void test8 ( ) throws Exception {
String s1 = "abc" ;
String s2 = "abc" ;
System. out. println ( s1 == s2) ;
System. out. println ( s1. equals ( s2) ) ;
}
@Test
public void test10 ( ) throws Exception {
String s1 = "ab" ;
String s2 = "abc" ;
String s3 = s1 + "c" ;
System. out. println ( s3 == s2) ;
System. out. println ( s3. equals ( s2) ) ;
3.其他api
@Test
public void test13 ( ) throws Exception {
String s1 = "heima" ;
String s2 = "" ;
String s3 = null;
System. out. println ( s1. isEmpty ( ) ) ;
System. out. println ( s2. isEmpty ( ) ) ;
System. out. println ( s3. isEmpty ( ) ) ;
}
@Test
public void testIndex ( ) throws Exception {
String s1 = "heima" ;
int index = s1. indexOf ( 'e' ) ;
System. out. println ( index) ;
String s2 = "heima" ;
int index2 = s1. indexOf ( 'z' ) ;
System. out. println ( index2) ;
String s = "woaiheima" ;
s. substring ( 4 ) ;
System. out. println ( s) ;
}
String substring ( int start) : 从指定位置开始截取字符串, 默认到末尾。
String substring ( int start, int end) : 从指定位置开始到指定位置结束截取字符串。范围左闭右开 "[ )"
"abcde" . substring ( 0 , 3 )
String newStr1 = "com.jd." . replaceAll ( "." , "/" ) + "Myclass.class" ;
String newStr2 = "com.jd." . replace ( '.' , '/' ) + "Myclass.class" ;
System. out. println ( newStr1) ;
System. out. println ( newStr2) ;