Java: Convert String “\uFFFF” into char

前端 未结 4 2001
眼角桃花
眼角桃花 2020-12-03 03:07

Is there a standard method to convert a string like \"\\uFFFF\" into character meaning that the string of six character contains a presentation of one unicode character?

相关标签:
4条回答
  • 2020-12-03 03:20
    char c = "\uFFFF".toCharArray()[0];
    

    The value is directly interpreted as the desired string, and the whole sequence is realized as a single character.

    Another way, if you are going to hard-code the value:

    char c = '\uFFFF';
    

    Note that \uFFFF doesn't seem to be a proper unicode character, but try with \u041f for example.

    Read about unicode escapes here

    0 讨论(0)
  • 2020-12-03 03:23
    String charInUnicode = "\\u0041"; // ascii code 65, the letter 'A'
    Integer code = Integer.parseInt(charInUnicode.substring(2), 16); // the integer 65 in base 10
    char ch = Character.toChars(code)[0]; // the letter 'A'
    
    0 讨论(0)
  • 2020-12-03 03:26

    The backslash is escaped here (so you see two of them but the s String is really only 6 characters long). If you're sure that you have exactly "\u" at the beginning of your string, simply skip them and converter the hexadecimal value:

    String s = "\\u20ac";
    
    char c = (char) Integer.parseInt( s.substring(2), 16 );
    

    After that c shall contain the euro symbol as expected.

    0 讨论(0)
  • 2020-12-03 03:29

    If you are parsing input with Java style escaped characters you might want to have a look at StringEscapeUtils.unescapeJava. It handles Unicode escapes as well as newlines, tabs etc.

    String s = StringEscapeUtils.unescapeJava("\\u20ac\\n"); // s contains the euro symbol followed by newline
    
    0 讨论(0)
提交回复
热议问题