Problem Description
输入一个字符串,判断其是否是C的合法标识符。
Input
输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然后是n行输入数据,每行是一个长度不超过50的字符串。
Output
对于每组输入数据,输出一行。如果输入数据是C的合法标识符,则输出”yes”,否则,输出“no”。
Sample Input
3
12ajf
fi8x_a
ff ai_2
Sample Output
no
yes
no
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();//接受回车键,否则str会接受换行符
while(n-->0){
String str=sc.nextLine();//接受一整行的字符串输入
char[] c=str.toCharArray();
boolean flag=true;
if(c[0]>='0'&&c[0]<='9'){
System.out.println("no");
continue;
}
for(int i=0;i<c.length;i++){
if(x(c[i])){
flag=false;
break;
}
}
// System.out.println(c.length);调试代码的,因为发现用String str=sc.next()输入,char[] c=str.toCharArray()分割字符串时遇到空格就不能继续分割
if(flag){
System.out.println("yes");
}else{
System.out.println("no");
}
}
}
public static boolean x(char c){
if((c>='0'&&c<='9')||(c>='a'&&c<='z')||(c>='A'&&c<='Z')||c=='_'){
return false;
}
return true;
}
}
本文介绍了一个Java程序,用于验证输入的字符串是否符合C语言标识符的规范。该程序通过检查字符串首字符不能为数字,并确保其余字符为字母、数字或下划线来实现这一功能。

1万+

被折叠的 条评论
为什么被折叠?



