今天去面试了一家外资公司,遇到一道笔试题
题目大概内容如下:
题目:判断邮箱地址是否为正确格式,如:aaa@foxmail.com;ABcd@sina.com.cn;
邮箱中除了"@"和".",其余字符全为字母。不要使用正则表达式,写出思路或画出流程图
下面是我整理出来的代码:
1 package com.b510.util;
2
3 /**
4 * 判断邮箱地址是否为正确格式,如:aaa@foxmail.com;ABcd@sina.com.cn; 邮箱中除了"@"和".",其余字符全为字母。
5 *
6 * @author hongten
7 * @date 3013-06-05
8 *
9 */
10 public class CheckEmail {
11
12 public static void main(String[] args) {
13 String email = "hongtenfoxmail.com.cn";
14 boolean isEmail = checkEmail(email);
15 String result = isEmail ? "正确" : "不正确";
16 System.out.println("邮箱 [" + email + "]格式是否正确:" + result);
17
18 }
19
20 /**
21 * 判断邮箱地址是否为正确格式,如:aaa@foxmail.com;ABcd@sina.com.cn; 邮箱中除了"@"和".",其余字符全为字母。
22 *
23 * @param email
24 * @return
25 */
26 public static boolean checkEmail(String email) {
27 boolean indexFlag = false;
28 boolean lastFlag = false;
29 String[] strs = email.split("@");
30 System.out.println(strs.length);
31 // 之前代码为:<code>if (strs.length > 0 && strs.length <= 2) {</code>,谢谢
32 // <a href="http://home.cnblogs.com/u/535203/">钢板</a>提出的bug
33 if (email.lastIndexOf("@") != -1 && strs.length <= 2) {
34 String index = strs[0];
35 String last = strs[1];
36 indexFlag = isAllChars(index);
37 String[] lastArray = last.split("\\.");
38 for (int j = 0; j < lastArray.length; j++) {
39 if (lastArray[j] == null || lastArray[j].equals("")) {
40 // 说明有".foxmail...com."这种情况
41 lastFlag = false;
42 break;
43 } else {
44 lastFlag = isAllChars(lastArray[j]);
45 if (!lastFlag) {
46 break;
47 }
48 }
49 }
50 return (indexFlag && lastFlag);
51 } else {
52 return false;
53 }
54 }
55
56 /**
57 * 判断一个字符串是否全为字母,此方法中,不管str中包含是否包含非字母字符,都会把str整个遍历
58 *
59 * @param str
60 * 所需判断的字符串
61 * @return
62 */
63 public static boolean isAllChar(String str) {
64 if (str == null || str.equals("")) {
65 return false;
66 }
67 int j = 0;
68 for (int i = 0; i < str.length(); i++) {
69 if ((str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
70 || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) {
71 j = j + 1;
72 }
73 }
74 return (j == str.length());
75 }
76
77 /**
78 * 判断一个字符串是否全为字母,此方法比上面的isAllChar方法效率要高,但是需要的是str中包含非字母字符在靠前面
79 * 如:"a2bcd",对于这个字符串,到字符"2"的时候就会终止判断
80 *
81 * @param str
82 * 所需判断的字符串
83 * @return
84 */
85 public static boolean isAllChars(String str) {
86 if (str == null || str.equals("")) {
87 return false;
88 }
89 boolean flag = true;
90 for (int i = 0; i < str.length(); i++) {
91 if ((str.charAt(i) < 'a' || str.charAt(i) > 'z')
92 && (str.charAt(i) < 'A' || str.charAt(i) > 'Z')) {
93 flag = false;
94 break;
95 }
96 }
97 return flag;
98 }
99 }
运行结果:
邮箱 [hongten@foxmail.com]格式是否正确:正确
邮箱 [hongten@foxmail..com.]格式是否正确:不正确
邮箱 [h2ongten@foxmail.com]格式是否正确:不正确
邮箱 [hongten@foxma2il.com]格式是否正确:不正确
邮箱 [@foxmail.com]格式是否正确:不正确
邮箱 [hon.gten@foxmail.com]格式是否正确:不正确
邮箱 [hongten@foxmail.com.cn]格式是否正确:正确