如何使用substring()获取带重音的字母?

huangapple go评论51阅读模式
英文:

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 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?

以下是要翻译的代码部分:

// GIVEN
String string = "ąbc";

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

// THEN
assertThat(substring).isEqualTo("ą");
英文:

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?

如何使用substring()获取带重音的字母?

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("ą");
    }

答案1

得分: 2

这可能是由于您的IDE控制台未正确配置字符编码而引起的问题。

无论可见字符如何,您可以通过打印字符的十六进制值来确认它是否是正确的字符:

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

该字符的结果应该是0105

要显示正确的字符,您可能需要更改Intellij的主题或配置。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月30日 03:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定