0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Java】見た目が一桁数字の String, char, int の型変換まとめ

Posted at
    String s = "1";
    char c = '1';
    int i = 1;

    // String
    String s_c = Character.toString(c);
    String s_i = Integer.toString(i);

    // char
    char c_s = s.charAt(0);
    char c_i = (char)('0' + i); // '0'のユニコードに i を足す

    // int
    int i_s = Integer.parseInt(s);
    int i_c = (int)(c - '0'); // c から'0'のユニコードを引く

    System.out.println("String: " + s + s_c + s_i);
    System.out.println("char: " + c + c_s + c_i);
    System.out.println("int: " + i + i_s + i_c);
String: 111
char: 111
int: 111

解説

String への変換

ラッパークラス.toString(元変数);

int への変換

String → int
Integer.parseInt( 元のString変数 );

char → int
(int)( 元のchar変数 - '0' );
ユニコードの差を取ることで、数字の charint に変換

char への変換

String → char
元のString変数.charAt( 変換する桁をintで指定 );
Stringクラスの charAt() メソッド で char に変換

int → char
(char)( '0' + 元のint変数 )
0 のユニコードを加算することで、元のint変数が表す数値のユニコードを算出

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?