I have just done this in eclipse:
String firstInput = removeSpaces(myIn.readLine());
String first = new String(firstInput.charAt(0));
However, eclipse complains that:
The constructor String(char) is undefined
How do I convert a char to a string then??
Thanks
I tried the substring method but it didn't work for some reason but gandalf's way works for me just fine! Very straightforward!
You can use String(char[] value) constructor to convert char array to string. This is the recommended way.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
Java Convert Int to String Using the ToString Method For example, the Integer class in Java has a static function named toString() that changes a given integer into a string. Let's look at the syntax for that next. Integer. toString(Variable/Number);
create a char array, set each of its elements, and then create a String from this char array (that's what would look the most like what you're trying to do); use a StringBuilder, append every character, then transform it into a String.
Easiest way?
String x = 'c'+"";
or of course
String.valueOf('c');
Instead of...
String first = new String(firstInput.charAt(0));
you could use...
String first = firstInput.substring(0,1);
substring(begin,end)
gives you a segment of a string - in this case, 1 character.
String x = String.valueOf('c');`
That's the most straight forward way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With