Java中char与int转换操作总结

最近做字符串相关题目的时候,总是遇到char与int之间相互转换。再次做个简短的总结,这里的char指的是ASCII 码值, ASCII 值总共有127位2^7-1。 其中我们常用的’a’为65,
char转int:

public class char_to_int
{
      public static void main(String args[])
      {
           char myChar = 'a';
           int  i = (int) myChar; // cast from a char to an int

           System.out.println ("ASCII value - " + i);
      }
}

int转char:

public class int_to_char
{
      public static void main(String args[])
      {
           int  a = 65;
           char myChar = (char) a; // cast from int to char

           System.out.println ("Char - " + myChar);
      }
}

两个char做差返回值为int,为他们之间的差值. 我们利用这个性质可以求char数字所代表的int值,
例如给定一个’5’的char,求对应的int值, 我们可以用给定的char来减去’0′,
‘5’ – ‘0’ = 5.
或者知道偏移量求某个字母,假如都是lowercase, (char)(5 + ‘a’) = ‘g’

还有我们做String到char[]转换的时候往往可以用String自带的方法:toCharArray()来获取char array。 或者遍历String的时候用charAt(i)方法获得某一位的char值。
在char的运算当中,我们往往用到Character API自带的方法来对char做些validation, 常用的方法有:
1 isLetter(): Determines whether the specified char value is a letter.

2 isDigit(): Determines whether the specified char value is a digit.

3 isWhitespace():Determines whether the specified char value is white space.

4 isUpperCase():Determines whether the specified char value is uppercase.

5 isLowerCase():Determines whether the specified char value is lowercase.

6 toUpperCase():Returns the uppercase form of the specified char value.

7 toLowerCase():Returns the lowercase form of the specified char value.

8 toString():Returns a String object representing the specified character value that is, a one-character string.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s