描述
C语言中的合法标识符的定义为:以下划线或字母开头的字母数字串(含下划线)。
完成一个程序实现对输入的n个字符串进行判定,是否为C语言的合法标识符。如果是则输出1,不是则输出0
输入
输入的第一行为一个数字,表明有几个输入字串。
后面每一行为一个长度不超过80的字符串。
输出
对所有输入的字符串进行判断,是合法标识符则输出1,回车。否则输出0,回车。样例输入
5 hello_world my god i _stdio 008A
样例输出
1 0 1 1 0
题解
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); while (n-- != 0) { String s = in.nextLine();// nextLine可以接收空格 if(s.matches("[a-z_A-Z][a-z_A-Z0-9]{0,}")) System.out.println(1); else System.out.println(0); } } }
这个题目不算难,但有几个地方需要注意。
1.nextLine()
在输入n和字符串之间需要加入一行读取换行符的代码。否则,将会出现程序运行的时候也会将输入的数字算入在内。
2.正则表达式
[a-z_A-Z][a-z_A-Z0-9]{0,}
这些字符表示:输入的字符串以字母和下划线“_”开头,由数字、字母和下划线“_”组成,长度大于0.
当然也可以用以下条件来判断,代码如下:
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int work; sc.nextLine(); String str=new String(); while(n--!=0) { work=1; str=sc.nextLine(); if(str.charAt(0)!='_'&&(!(str.charAt(0)>='a'&&str.charAt(0)<='z'))&&(!(str.charAt(0)>='A'&&str.charAt(0)<='Z'))) work=0; for(int j=0;j<str.length();j++) { if(str.charAt(j)==' ') work=0; } System.out.println(work); } } }