Java String構造方法


感謝大神: https://www.cnblogs.com/JavaSubin/p/5450849.html

 

 

 

 

 

2,常見構造方法

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):把字符串常量值轉成字符串

 -----------------------------------------------------------------------------------------------------------------------------

構造方法:

1)無參構造方法

String()

String s1 = new String();
System.out.println(s1);// 啥也不輸出

 

2)參數為字符串類型

String(String original)

String s6 = new String("KobeBryant");
System.out.println(s6);

 

3)參數為 byte 數組類型

String(byte[] bytes)
String(byte[] bytes, Charset charset)               

byte 是網絡傳輸或存儲的序列化形式,所以在很多傳輸和存儲的過程中需要將 byte[] 數組和 String 進行相互轉化。

有關 IO 流的代碼中會出現這個構造方法,字符編碼導致的亂碼問題也是比較多的,這里需要注意:一旦看到 byte 數組,一定要想到編碼問題。

經常會用到 getBytes【字符串轉字符數組】(Charset charset) 方法:

byte[] arr1 = { 97, 98, 99, 100 };
String s2 = new String(arr1);
System.out.println(s2);//abcd

 

4)參數為 char 數組類型

char[] arr3 = { 'a', 'b', 'c', 'd', 'e' }; // 將字符數組轉換成字符串
String s4 = new String(arr3);
System.out.println(s4);//abcde

 

5)參數為 StringBuilder 或者 StringBuffer 類型

String(StringBuffer buffer)
                       (Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.)
String(StringBuilder builder)
                        (Allocates a new string that contains the sequence of characters currently contained in the string builder argument.)

StringBuilder sbb = new StringBuilder();
sbb.append("hello ").append("world");
String str1 = sbb.toString(); //hello world  

 

 

 

String.valueOf() 方法的使用

1. 由 基本數據型態轉換成 String
String 類別中已經提供了將基本數據型態轉換成 String 的 static 方法
也就是 String.valueOf() 這個參數多載的方法
有下列幾種
String.valueOf(boolean b) : 將 boolean 變量 b 轉換成字符串
String.valueOf(char c) : 將 char 變量 c 轉換成字符串
String.valueOf(char[] data) : 將 char 數組 data 轉換成字符串
String.valueOf(char[] data, int offset, int count) :
將 char 數組 data 中 由 data[offset] 開始取 count 個元素 轉換成字符串
String.valueOf(double d) : 將 double 變量 d 轉換成字符串
String.valueOf(float f) : 將 float 變量 f 轉換成字符串
String.valueOf(int i) : 將 int 變量 i 轉換成字符串
String.valueOf(long l) : 將 long 變量 l 轉換成字符串
String.valueOf(Object obj) : 將 obj 對象轉換成 字符串, 等於 obj.toString()
用法如:
int i = 10;
String str = String.valueOf(i);
這時候 str 就會是 "10"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM