在 Java 中,如何檢查一個字串是否只包含 ASCII 字元?
使用正則表示式
您可以使用以下正則表示式來查詢特定的字串值是否包含 ASCII 字元:
\A\p{ASCII}*\zString 類中的 matches() 方法接受一個正則表示式,並驗證當前字串是否與給定表示式匹配。如果是,則返回 true,否則返回 false。
因此,透過將上述指定的正則表示式作為引數傳遞給輸入/所需字串,呼叫 matches() 方法。
示例
import java.util.Scanner;
public class OnlyASCII {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String input = sc.nextLine();
//Verifying for ACCII
boolean result = input.matches("\A\p{ASCII}*\z");
if(result) {
System.out.println("String approved");
} else {
System.out.println("Contains non-ASCII values");
}
}
}輸出1
Enter a string value: hello how are you String approved
輸出2
Enter a string value: whÿ do we fall Contains non-ASCII values
驗證每個字元
如果您將 ASCII 字元轉換為整數,所有結果都將小於或等於 127。
String 類中的 charAt() 方法接受一個整數值並返回指定索引處的字元。
使用此方法檢索給定字串中的每個字元,並驗證它們是否大於 127。
示例
import java.util.Scanner;
public class OnlyASCII {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String input =sc.next();
//Converting given string to character array
char charArray[] = input.toCharArray();
boolean result = true;
for(int i = 0; i < input.length(); i++) {
int test = (int)input.charAt(i);
if (test<=127) {
result = true;
}else if (test >127){
result = false;
}
}
System.out.println(result);
if(result) {
System.out.println("String approved");
}else {
System.out.println("Contains non-ASCII values");
}
}
}輸出1
Enter a string value: whÿ false Contains non-ASCII values
輸出2
Enter a string value: hello true String approved
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP