我有一個int int範圍0-255,我想創建一個字符串(長度爲1),以便該單個字符的ASCII值是指定的整數。如何將ASCII碼(0-255)轉換爲關聯字符的字符串?
有沒有一種簡單的方法在Java中做到這一點?
例如:
65 -> "A"
102 -> "f"
我有一個int int範圍0-255,我想創建一個字符串(長度爲1),以便該單個字符的ASCII值是指定的整數。如何將ASCII碼(0-255)轉換爲關聯字符的字符串?
有沒有一種簡單的方法在Java中做到這一點?
例如:
65 -> "A"
102 -> "f"
String.valueOf
(
Character.toChars(int)
)
假設整數,如你說,0和255之間,就會得到一個陣列與單個字符從Character.toChars
返回,這將在傳遞到String.valueOf
時變成單字符字符串。
使用Character.toChars
最好涉及來自int
到char
(即(char) i
)鑄造了許多原因,其中包括,如果你沒有正確地驗證了整數,而中投將吞下錯誤(Character.toChars
將拋出IllegalArgumentException
方法每narrowing primitive conversions specification),可能會提供一個不是你想要的輸出。
假設整數是範圍在0到255之間(因爲你聲明你做......並且如問題所指定的那樣),使用'toChars'是不必要和不理想的。 –
「Character.toString((char)i)'比'String.valueOf(Character.toChars(i))'快完全正確。在我的機器上運行一個在給定範圍內轉換1,000,000個隨機整數(100倍,以保證安全)的快速基準測試平均時間爲153.07納秒,而862.39納秒。但是,在任何有趣的應用中,都會有更重要的事情需要優化。在[0,255]範圍之外的安全,確定性處理和擴展容易度的附加價值,應該被要求超過次要表現。 – zjs
new String(new char[] { 65 }))
您將得到一個長度爲1的字符串,其單個字符具有(ASCII)代碼65.在Java字符串中是數字數據類型。
System.out.println((char)65);
將打印 「A」
REPL提示:如果您碰巧使用JShell(Java 9),則可以省略System.out。只需輸入'(char)65'來找出它是什麼字符。 – DavidS
人們可以從一個迭代到z這樣
int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}
做同樣的一個簡單的方法:
類型轉換整數性格,讓int n
是整數, 然後:
Char c=(char)n;
System.out.print(c)//char c will store the converted value.
int number = 65;
char c = (char)number;
它是一個簡單的解決方案
這是一個實例,其示出了通過轉換一個int爲char,可以確定相應的字符轉換成ASCII碼。
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println(i + ". " + (char)i);
}
}
}
上面的答案只解決問題附近。繼承人您的回答:
Integer.decode(Character.toString(char c));
for (int i = 0; i < 256; i++) {
System.out.println(i + " -> " + (char) i);
}
char lowercase = 'f';
int offset = (int) 'a' - (int) 'A';
char uppercase = (char) ((int) lowercase - offset);
System.out.println("The uppercase letter is " + uppercase);
String numberString = JOptionPane.showInputDialog(null,
"Enter an ASCII code:",
"ASCII conversion", JOptionPane.QUESTION_MESSAGE);
int code = (int) numberString.charAt(0);
System.out.println("The character for ASCII code "
+ code + " is " + (char) code);
請解釋你的答案 – want2learn
這不是如上所述的重複。這不是從整數轉換,而是從char(ascii) –
*不是*「如何從int轉換爲字符串?」的副本......無論如何,FWIW,ASCII只有7位值[0,127]; - ) – 2011-10-08 00:33:03
@phooji我認爲,後sais如何轉換1 - >「1」等' – Belgi