Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีตรวจสอบว่า String มีแค่ ASCII Characters ใน Java

มี 2 วิธีหลัก: Regex และ Check Character Code

วิธีที่ 1: ใช้ Regex (กระชับ)

Regex: \\A\\p{ASCII}*\\z

  • \\A = Start of String
  • \\p{ASCII} = ASCII Character (U+0000 to U+007F)
  • * = 0 or more
  • \\z = End of String
import java.util.Scanner;

public class CheckASCII {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter string: ");
        String input = sc.nextLine();
        
        // Check with Regex
        boolean isASCII = input.matches("\\A\\p{ASCII}*\\z");
        
        if (isASCII) {
            System.out.println("String approved (ASCII only)");
        } else {
            System.out.println("Contains non-ASCII values");
        }
    }
}

ผลลัพธ์

Enter string: hello how are you
String approved (ASCII only)

Enter string: whÿ do we fall
Contains non-ASCII values

วิธีที่ 2: ตรวจสอบ Character Code ทุกตัว (Manual)

ASCII Code = 0-127 (0x00-0x7F)

public class CheckASCIIManual {
    public static boolean isASCII(String str) {
        for (int i = 0; i < str.length(); i++) {
            int codePoint = str.codePointAt(i); // รองรับ Supplementary Characters
            if (codePoint > 127) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        String[] tests = {"Hello", "Hellö", "สวัสดี", "😀"};
        for (String s : tests) {
            System.out.println(s + " -> " + (isASCII(s) ? "ASCII" : "Non-ASCII"));
        }
    }
}

ผลลัพธ์

Hello -> ASCII
Hellö -> Non-ASCII (ö = U+00F6 > 127)
สวัสดี -> Non-ASCII (Thai > 127)
😀 -> Non-ASCII (Emoji = U+1F600 > 127)

วิธีที่ 3: ใช้ Charset/StandardCharsets (Java 7+)

import java.nio.charset.StandardCharsets;
import java.nio.charset.CharsetEncoder;

public class CheckASCIICharset {
    public static boolean isASCII(String str) {
        CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
        return encoder.canEncode(str);
    }
}

เปรียบเทียบ

วิธี ข้อดี ข้อเสีย
Regex matches() กระชับ One-liner Compile Regex ทุกครั้ง (Slow สำหรับ Loop ใหญ่)
Manual Loop ควบคุมได้, รองรับ Code Point Verbose
CharsetEncoder Standard, รองรับทุก Charset Overhead Object Creation

Performance Tip (High Volume)

// Pre-compile Pattern
private static final Pattern ASCII_PATTERN = Pattern.compile("\\A\\p{ASCII}*\\z");

public static boolean isASCIIFast(String str) {
    return ASCII_PATTERN.matcher(str).matches();
}

สรุป

  • General Use: str.matches("\\A\\p{ASCII}*\\z")
  • High Performance: Pre-compile Pattern หรือ Manual Loop
  • Enterprise: CharsetEncoder.canEncode() (Reusable, Standard)
  • ASCII = Code Point 0-127 (Basic Latin, Control Chars, Digits, Punctuation)