บทนำ
ในบทความนี้ เราจะเรียนรู้วิธีการหา Unicode Code Point ที่ดัชนี (Index) ที่กำหนด แต่ละตัวอักษรถูกแทนด้วย Unicode code point Code point คือค่าจำนวนเต็มที่ระบุตัวอักษรเฉพาะตัวได้อย่าง unik Unicode characters สามารถเข้ารหัสได้ด้วย encoding ต่างๆ เช่น UTF-8 หรือ UTF-16
ตัวอย่างการทำงาน
อินพุทตัวอย่าง:
Input String: Java Program Index value: 5
เอาต์พุทที่คาดหวัง:
Unicode Point: 80
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศสตริง input_string และจำนวนเต็ม index, result ขั้นตอนที่ 3 - กำหนดค่า ขั้นตอนที่ 4 - ใช้ฟังก์ชัน codePointAt() ดึงค่า code point เก็บไว้ใน result ขั้นตอนที่ 5 - แสดงผลลัพธ์ ขั้นตอนที่ 6 - จบการทำงาน
ตัวอย่างที่ 1: เขียนในฟังก์ชัน main โดยตรง
import java.io.*;
public class UniCode {
public static void main(String[] args) {
System.out.println("Required packages have been imported");
String input_string = "Java Program";
System.out.println("\nThe string is defined as: " + input_string);
int result = input_string.codePointAt(5);
System.out.println("The unicode point at index 5 is : " + result);
}
}
เอาต์พุท
Required packages have been imported The string is defined as: Java Program The unicode point at index 5 is : 80
ตัวอย่างที่ 2: ใช้เมธอดแยก (Object-Oriented Style)
import java.io.*;
public class UniCode {
static void unicode_value(String input_string, int index) {
int result = input_string.codePointAt(index);
System.out.println("The unicode point at index " + index + " is : " + result);
}
public static void main(String[] args) {
System.out.println("Required packages have been imported");
String input_string = "Java Program";
System.out.println("\nThe string is defined as: " + input_string);
int index = 5;
unicode_value(input_string, index);
}
}
เอาต์พุท
Required packages have been imported The string is defined as: Java Program The unicode point at index 5 is : 80
การอธิบายผลลัพธ์:
สตริง "Java Program" ดัชนี 0-10:
Index: 0 1 2 3 4 5 6 7 8 9 10 Char: J a v a P r o g r a m Code: 74 97 118 97 32 80 114 111 103 114 97 109
ดัชนี 5 คือ 'P' → Unicode code point = 80 (0x50)
เมธอดเกี่ยวข้อง:
codePointAt(int index)- code point ที่ดัชนี indexcodePointBefore(int index)- code point ก่อนดัชนี indexcodePointCount(int begin, int end)- นับ code points ในช่วงoffsetByCodePoints(int index, int codePointOffset)- หาดัชนีใหม่จาก code point offset
หมายเหตุ: สำหรับตัวอักษรภาษาไทย/อีโมจิ ที่ใช้ surrogate pairs (2 char = 1 code point) ให้ใช้ codePointAt() ไม่ใช่ charAt()