javaunicode-string

How do I get accented letter using substring()?


I have the following string: ąbc. I'd like to get its first character, ie. ą. When I use use the following code "ąbc".substring(0,1) I get the correct result using jshell. However, when using IntelliJ, I get a instead of ą. What's wrong?

enter image description here

The following unit test works fine (in IntelliJ and in Maven):

    @Test
    void test() {
        // GIVEN
        String string = "ąbc";

        // WHEN
        final String substring = string.substring(0, 1);

        // THEN
        assertThat(substring).isEqualTo("ą");
    }

Solution

  • This is probably an issue with your IDE console not being configured correctly for the character encoding.

    Regardless of the visible character you can confirm it is the right character by printing the hexadecimal value of the character:

          System.out.println(String.format("%04x", (int) "ąbc".charAt(0)));
    

    The result should be 0105 for that character.

    To display the correct character you may need to change Intellij's theme or configuration.