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

JavaStringChar

Java Problem Overview


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 Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

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

Solution 3 - Java

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.

Solution 4 - Java

String someString = "" + c;
char c = someString.charAt(0);

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

I like to do something like this:

String oneLetter = "" + someChar;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - JavapolygenelubricantsView Answer on Stackoverflow
Solution 2 - JavaBryanDView Answer on Stackoverflow
Solution 3 - JavahelpermethodView Answer on Stackoverflow
Solution 4 - JavafastcodejavaView Answer on Stackoverflow
Solution 5 - JavaMyUserQuestionView Answer on Stackoverflow
Solution 6 - JavaSantosh KulkarniView Answer on Stackoverflow
Solution 7 - JavaRomanView Answer on Stackoverflow