Paket2001
Paket2001

Reputation: 450

Parse a String to a char?

So in Java how is it possible to pase a String like ("\u000A") to a char? I got that String from a file, so i can't say something like this: char c = '\u000A';

Upvotes: 1

Views: 1138

Answers (4)

Hot Licks
Hot Licks

Reputation: 47729

In answer to Oscar Lopez, this compiles and executes just fine:

public class TestUnicode {
    static public void main(String[] argv) {
        System.out.println("This is one line"); \u000A System.out.println("This is another line");
    }
}

The important thing to understand is that, in the Java compiler, \uXXXX characters are translated as the programs is being scanned, not as the characters are being inserted into a string literal (which is the norm for other \ escapes). Replace the \u000A above with \n and the program will not compile, but rather the compiler will report "Illegal character: \92" (and 92 is the decimal value for \).

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200166

Without extra libraries, you can use the fact that this is just the hexadecimal value of the char. This expression's value is that character:

(char)Integer.parseInt(input.substring(2, 16))

The technique works even for surrogate pairs because then you'd have two separate \u notations for the pair.

Upvotes: 0

auselen
auselen

Reputation: 28087

Check StringEscapeUtils

Escapes and unescapes Strings for Java, Java Script, HTML and XML.

This should work for what you want

char c = StringEscapeUtils.unescapeJava("\\u000A").charAt(0);

Double back slash is to encode "\u000A" in Java.

Upvotes: 3

Óscar López
Óscar López

Reputation: 236034

Yes you can, this is perfectly valid code:

char c = '\uD840';

The example in your code, '\u000A' happens to be a non-valid Unicode character (probably a decoding problem when reading?). But all valid Unicode characters can be passed along between single quotes.

Upvotes: 1

Related Questions