簡體   English   中英

JAVA - 字符到整數的轉換

[英]JAVA - Char to Int Conversion

int x='1';
    int y='0';
    System.out.println(x);
    System.out.println(y);

O/P 為 49、48 而

 int x=s.charAt(1);
    int y=s.charAt(0);
    System.out.println(x);
    System.out.println(y);

O/P 為 50, 49 是什么原因

charAt() 方法用於字符串 object 並獲取索引中的字符

charAt(int 索引)

String s="Hello"
int x=s.charAt(1) //output: e
System.out.println(x)
// will be the ascii code for the letter

在你的代碼中沒有s string ,所以它會是錯誤的

您可以使用轉換運算符將 int 轉換為 char 並將 char 轉換為 int。

這是一個例子:

char c1 = 'b';      //the character 'b' 
int  n = (int) c1;  //convert character to int (ascii code of 'b')
char c2 = (char) n; //convert int to a char 
        
System.out.println(c1);
System.out.println(n);
System.out.println(c2);

output

b
98
b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM