如何驗證 Java 中的字串 (用於字母)?
若要驗證一個字串用於字母,你可以將字串中的每個字元都與英語字母中的字元(大小寫)進行比較,或使用正則表示式。
示例 1
以下程式從使用者那裡接受一個字串值(名稱),並透過將其中的每個字元都與英語字母中的字元進行比較,找出給定的字串是否是一個專有名稱。
import java.util.Scanner;
public class ValidatingString {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String str = sc.next();
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!(ch >= 'a' && ch <= 'z'|| ch >= 'A' && ch <= 'Z')) {
flag = false;
}
}
if(flag)
System.out.println("Given string is a proper name.");
else
System.out.println("Given string is a proper string is not a proper name.");
}
}輸出 1
Enter your name: krishna45 Given string is a proper string is not a proper name.
輸出 2
Enter your name: kasyap Given string is a proper name.
示例 2
以下程式從使用者那裡接受一個字串值(名稱),並使用正則表示式找出給定的字串是否是一個專有名稱。
import java.util.Scanner;
public class ValidatingString2 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String str = sc.next();
if((!str.equals(null))&&str.matches("^[a-zA-Z]*$"))
System.out.println("Given string is a proper name.");
else
System.out.println("Given string is a proper string is not a proper name.");
}
}輸出 1
Enter your name: krishna45 Given string is a proper string is not a proper name.
輸出 2
Enter your name: kasyap Given string is a proper name.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP