In Java how does one turn a String into a char or

2019-01-16 15:56发布

Is there a way to turn a char into a String or a String with one letter into a char (like how you can turn an int into a double and a double into an int)? (please link to the relevant documentation if you can).

How do I go about finding something like this that I'm only vaguely aware of in the documentation?

标签: java string char
7条回答
戒情不戒烟
2楼-- · 2019-01-16 16:02

I like to do something like this:

String oneLetter = "" + someChar;
查看更多
\"骚年 ilove
3楼-- · 2019-01-16 16:03
char firstLetter = someString.charAt(0);
String oneLetter = String.valueOf(someChar);

You find the documentation by identifying the classes likely to be involved. Here, candidates are java.lang.String and java.lang.Character.

You should start by familiarizing yourself with:

  • Primitive wrappers in java.lang
  • Java Collection framework in java.util

It also helps to get introduced to the API more slowly through tutorials.

查看更多
Explosion°爆炸
4楼-- · 2019-01-16 16:07
String someString = "" + c;
char c = someString.charAt(0);
查看更多
祖国的老花朵
5楼-- · 2019-01-16 16:09

As no one has mentioned, another way to create a String out of a single char:

String s = Character.toString('X');

Returns a String object representing the specified char. The result is a string of length 1 consisting solely of the specified char.

查看更多
疯言疯语
6楼-- · 2019-01-16 16:11

String.valueOf('X') will create you a String "X"

"X".charAt(0) will give you the character 'X'

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-16 16:16

In order to convert string to char

 String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();
查看更多
登录 后发表回答