繁体   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