62

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
David
  • 14,569
  • 34
  • 78
  • 107

7 Answers7

98
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.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
16

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

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

Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
BryanD
  • 1,897
  • 12
  • 13
13

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.

helpermethod
  • 59,493
  • 71
  • 188
  • 276
2
String someString = "" + c;
char c = someString.charAt(0);
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 1
    The `"" + 'c'` uses autoboxing and is not recommended, because it first does `"" + Character.toString('c')` and then `"" + "c"` and then `"c"`. It does the extra `"" + "c"` operation, which can slow down the program if used too often. – hyper-neutrino Aug 07 '15 at 19:48
1
String g = "line";
//string to char
char c = g.charAt(0);
char[] c_arr = g.toCharArray();
//char to string
char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
//(or iterate the charArray and append each character to str -> str+=charArray[i])

//or String s= new String(chararray);

MyUserQuestion
  • 295
  • 1
  • 9
-1

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();
-2

I like to do something like this:

String oneLetter = "" + someChar;
Roman
  • 64,384
  • 92
  • 238
  • 332
  • 6
    I strongly dislike it, because it doesn't convey the intent. You don't want to do any addition or concatenation, so `+` is not the right thing to use here. – Joachim Sauer Mar 12 '10 at 09:44