Char 배열 내 유니코드 코드 포인트 수 세기

JavaBeginner
지금 연습하기

소개

Java 의 codePointCount() 메서드는 지정된 char 배열의 하위 배열에 대한 총 유니코드 코드 포인트 수를 반환합니다. 이는 Java 의 Character 클래스에 속합니다. offset 매개변수는 char 배열의 시작 인덱스를 나타내며, count 매개변수는 고려할 문자 수를 결정하는 데 사용됩니다.

Java 파일 생성

다음 명령을 사용하여 ~/project 디렉토리에 CharacterCodepointCount.java라는 파일을 생성합니다.

touch ~/project/CharacterCodepointCount.java

텍스트 편집기에서 파일을 엽니다.

codePointCount() 메서드 선언

CharacterCodepointCount 클래스 내에서 codePointCount() 메서드를 선언합니다. 이 메서드는 char[] a, int offset, 및 int count의 세 가지 매개변수를 받습니다. 이 메서드는 main 메서드에서 직접 호출할 것이므로 static 메서드로 선언해야 합니다.

public class CharacterCodepointCount {
    public static int codePointCount(char[] a, int offset, int count) {
        // code for the method
    }
}

위 코드에서 문자 배열 (char[] a), 시작 지점의 정수 값 (int offset), 그리고 개수의 정수 값 (int count) 을 매개변수로 받는 static 메서드 codePointCount()를 선언했습니다.

codePointCount() 메서드 구현

codePointCount() 메서드 내에서 지정된 char 배열의 하위 배열에 대한 총 유니코드 코드 포인트 수를 반환하는 코드를 작성합니다.

public class CharacterCodepointCount {
    public static int codePointCount(char[] a, int offset, int count) {
        return Character.codePointCount(a, offset, count);
    }
}

위 코드에서 Character 클래스의 codePointCount() 메서드를 사용하여 지정된 char 배열의 하위 배열에 대한 총 유니코드 코드 포인트 수를 반환했습니다.

main 메서드에서 codePointCount() 메서드 사용

main() 메서드에서 codePointCount() 메서드를 사용하여 지정된 char 배열의 하위 배열에 대한 총 유니코드 코드 포인트 수를 찾습니다.

public class CharacterCodepointCount {
    public static void main(String[] args) {
        char[] ch1 = new char[] { 'j', 'a', 'v', 'a', '1', '2', '3' };
        int offset1 = 0, count1 = 3;
        int r1 = codePointCount(ch1, offset1, count1);
        System.out.println("The number of Unicode code points in the subarray is: " + r1);

        String s1 = "Hello World";
        int offset2 = 2, count2 = 4;
        int r2 = s1.codePointCount(offset2, count2);
        System.out.println("The number of Unicode code points in the subarray is: " + r2);
    }

    public static int codePointCount(char[] a, int offset, int count) {
        return Character.codePointCount(a, offset, count);
    }
}

위 코드에서 두 개의 문자 배열을 생성하고 이를 codePointCount() 메서드의 매개변수로 사용했습니다. 그런 다음 println() 메서드를 사용하여 지정된 char 배열의 하위 배열에 대한 총 유니코드 코드 포인트 수를 출력했습니다.

코드 컴파일 및 실행

파일을 저장하고 터미널을 엽니다. 다음 명령을 사용하여 코드를 컴파일합니다.

javac ~/project/CharacterCodepointCount.java

오류가 없으면 다음 명령으로 프로그램을 실행합니다.

java CharacterCodepointCount

출력 결과는 다음과 같습니다.

The number of Unicode code points in the subarray is: 3
The number of Unicode code points in the subarray is: 4

요약

이 랩에서는 Java 에서 codePointCount() 메서드를 사용하여 지정된 char 배열의 하위 배열에 대한 총 유니코드 코드 포인트 수를 찾는 방법을 배웠습니다. 또한 Java 파일을 생성하고, 메서드를 구현하고, 배열과 문자열을 메서드 매개변수로 사용하고, 터미널에서 Java 프로그램을 컴파일하고 실행하는 방법도 배웠습니다.