java中將字元(Char)轉換為字串的四種方式

來源:互聯網
上載者:User


方法一:使用Character.toString()

Character類提供了一個靜態方法toString()用來將字元轉換成字串。

char ch = 'U';
String charToString = Character.toString(ch);

 

方法二:使用字串串連符

當我們使用字串串連符的時候,會自動將其他類型的變數轉換為字串類型,如下:

char ch = 'U';
String str = "" + ch;

 
方法三:使用匿名數組(anonymous array)

java中的匿名數組可以被用來封裝一個單獨的字元到字元數組,然後將這個字元數組作為String的構造器參數。

char ch = 'U';
String fromChar = new String(new char[]{ch});

方法四:使用String.valueOf()

 

char ch = 'U';
String valueOfchar = String.valueOf(ch);

 
下面是完整的範例程式碼:


public class CharToStringExample {
 
public static void main(String args[]) {
char ch = 'U';
 
// char to string using Character class
String charToString = Character.toString(ch);
System.out.println("Converting Char to String using Character class: " + charToString);
 
// char to String using String concatenation
String str = "" + ch;
System.out.println("Converting Char to String using String concatenation: " + str);
 
// char to String using anonymous array
String fromChar = new String(new char[] { ch });
System.out.println("Converting Char to String using anonymous array: " + fromChar);
 
// char to String using String valueOf
String valueOfchar = String.valueOf(ch);
System.out.println("Converting Char to String using String valueOf: " + valueOfchar);
 
}
 
}
 
Output:
Converting Char to String using Character class: U
Converting Char to String using String concatenation: U
Converting Char to String using anonymous array: U
Converting Char to String using String valueOf: U

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.