📜  Java中的字符.getDirectionality() 方法及示例(1)

📅  最后修改于: 2023-12-03 15:31:59.124000             🧑  作者: Mango

Java 中的字符.getDirectionality() 方法及示例

在 Java 中,字符类型有 charCharacter 两种。其中,Character 类中提供了 getDirectionality(char ch) 方法,用于获取一个字符的方向性。该方法返回 Unicode 字符的方向性常量,用于指示该字符是从左到右的、从右到左的还是既不是。返回值为 CHARACTER_DIRECTIONALITY_LEFT_TO_RIGHT (从左到右)、CHARACTER_DIRECTIONALITY_RIGHT_TO_LEFT (从右到左)、CHARACTER_DIRECTIONALITY_EUROPEAN_NUMBER (欧洲数字)、CHARACTER_DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR (欧洲数字分隔符)、CHARACTER_DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR (欧洲数字终止符)、CHARACTER_DIRECTIONALITY_ARABIC_NUMBER (阿拉伯数字)、CHARACTER_DIRECTIONALITY_COMMON_NUMBER_SEPARATOR (普通数字分隔符)、CHARACTER_DIRECTIONALITY_NONSPACING_MARK (非间距标记)、CHARACTER_DIRECTIONALITY_BOUNDARY_NEUTRAL (边界中立)。

下面是 Character.getDirectionality(char ch) 方法的语法:

public static byte getDirectionality(char ch)

接下来,我们来看一个示例:

public class CharDirectionalityExample {
    public static void main(String[] args) {
        String str = "June 9th, 2022";
        char[] chArray = str.toCharArray();

        for (char ch : chArray) {
            System.out.printf("Character '%c' is of type: %d\n", ch, Character.getDirectionality(ch));
        }
    }
}

在这个示例中,我们将一个字符串转换为字符数组,并使用 for-each 循环迭代该数组中的每个字符。在每次迭代中,我们打印出该字符及其类型。这里我们使用了 Character.getDirectionality(char ch) 方法来获取字符的方向性。

输出结果如下:

Character 'J' is of type: 0
Character 'u' is of type: 0
Character 'n' is of type: 0
Character 'e' is of type: 0
Character ' ' is of type: 13
Character '9' is of type: 10
Character 't' is of type: 0
Character 'h' is of type: 0
Character ',' is of type: 2
Character ' ' is of type: 13
Character '2' is of type: 10
Character '0' is of type: 10
Character '2' is of type: 10
Character '2' is of type: 10

此示例中,我们使用 getDirectionality() 方法来获取每个字符的类型。注意,在输出结果中,空格的类型为 CHARACTER_DIRECTIONALITY_PARAGRAPH_SEPARATOR (段落分隔符)。