面试被虐了一波,于是痛定思痛改头换面,不得不说敲代码中笔试和用电脑还是有很大区别的.
题目大概是这样的
假设限定输入用户输入电子邮箱地址,用户名必须只包含英文字母,数字和"-","_",","
* ,并且必须以字母和数字开头,邮件服务域名只包含字母和数字
* 请使用你所熟悉的编程语言编写一个函数,该函数判断输入的字符串是否为一个电子邮箱,注(不能使用正则表达式)
我来写下我大概的思路
(基本上都用Ascii来限定这个字符串)
public class First {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("请输入用户名:");
String email = input.nextLine();
if((a(email) == true) && (b(email) == true) && (c(email) == true)){
System.out.println("正确");
}else{
System.out.println("错误");
}
}
public static boolean a(String email){//用于验证数字和字母开头
char c = email.charAt(0);
int a = (int)c;
if((a>=48 && a<=57) || ((a>=65&&a<90) || (a>=97&&a<=122))){//利用ASCII码来判断
return true;
}else{
return false;
}
}
public static boolean b(String email){//用于验证是否只包含英文字母,数字和"-","_",","
String a = null;
int j = email.indexOf("@");
a = email.substring(1,j);//需要对字符串进行分割,处理@前面的除了首之母之外的用户字母
for(int i=0;i<a.length();i++){
int c = a.charAt(i);
if((c>=48 && c<=57) || ((c>=65&&c<90) || (c>=97&&c<=122)) || c==45 || c==44 || c==95 ){//利用ASCII码来判断
return true;
}else {
return false;
}
}
return true;
}
public static boolean c(String email){//用于验证邮件服务域名只包含字母和数字
String a = null;
int j = email.indexOf("@");
a = email.substring(j+1, email.length());
for(int i=0;i<a.length();i++){
int c = a.charAt(i);
if((c>=48 && c<=57) || ((c>=65&&c<90) || (c>=97&&c<=122)) || c==46){//利用ASCII码来判断
return true;
}else {
return false;
}
}
return true;
}
}