简体   繁体   中英

Java: Converting a char to a string

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

EDIT

I tried the substring method but it didn't work for some reason but gandalf's way works for me just fine! Very straightforward!

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

这是最直接的方式。

为什么不使用子串?

String first = firstInput.substring(0, 1);
String firstInput = removeSpaces(myIn.readLine());
String first = firstInput.substring(0,1);

This has an advantage that no new storage is allocated.

你可以这样做:

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

String.valueOf() to Convert Char to String

The String class has a static method valueOf() that is designed for this particular use case. Here you can see it in action:

public class CharToString {
public static void main(String[] args) {
    char givenChar = 'c';
    String result = String.valueOf(givenChar);

    //check result value string or char 
    System.out.println(result.equals("c")); 
    System.out.println(result.equals(givenChar));
  }
}

Output::

true
false

Character.toString() to Convert Char to String

We can also use the built-in method of Character class to convert a character to a String.

The below example illustrates this:

public class CharToString {
public static void main(String[] args) {
    char givenChar = 'c';
    String result = Character.toString(givenChar);

    //check result value string or char
    System.out.println(result.equals("c"));
    System.out.println(result.equals(givenChar));
    }
 }

Output::

true
false

String Concatenation to Convert Char to String

This method simply concatenates the given character with an empty string to convert it to a String.

The below example illustrates this:

public class CharToString {
public static void main(String[] args) {
    char myChar = 'c';
    String charToString = myChar + "";

    //check result value string or char
    System.out.println(charToString.equals("c"));
    System.out.println(charToString.equals(myChar));
   }
}

Output::

true
false

However, this is the least efficient method of all since the seemingly simple concatenation operation expands to new StringBuilder().append(x).append("").toString(); which is more time consuming than the other methods we discussed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM