我试图通过检查字符串是否包含在数组中设置的特殊字来检查字符串是否有效
String email = "this@webmaster";
tv.setText(Boolean.toString(checkEmailValidity(email)));
}
public boolean checkEmailValidity(String email) {
String[] specialWords = {"webmaster", "government"};
if( email.contains(specialWords.toString())||email.contains(" ")){
return false;
}
return true;
}
结果始终为true,因此使用specialWords检查电子邮件的语句不好。我该怎么办?
答案 0 :(得分:1)
如果您使用的是Java 8,则可以这样做
return Arrays.stream(specialwords).parallel().anyMatch(email::contains);
答案 1 :(得分:0)
试试这个:
public static boolean checkEmailValidity(String email) {
String[] specialWords = {"webmaster", "government"};
Set<String> set = new HashSet<String>(Arrays.asList(specialWords));
return set.contains(email);
}
这是您的代码:
public static boolean checkEmailValidity(String email) {
String[] specialWords = {"webmaster", "government"};
boolean flag = false;
if (!email.contains(" ")) {
for (int index = 0; index < specialWords.length; index++) {
if (email.contains(specialWords[index].toString())) {
flag = false;
break;
} else {
flag = true;
}
}
}
return flag;
}
答案 2 :(得分:0)
Pattern regex = Pattern.compile("\\b(?:webmaster|government)\\b");
Matcher regexMatcher = regex.matcher(email);
boolean contains = regexMatcher.find();
答案 3 :(得分:-1)
String email = "this@webmaster";
tv.setText(Boolean.toString(checkEmailValidity(email)));
public boolean checkEmailValidity(String email) {
String[] specialWords = {"webmaster", "government"};
if( email.contains(specialWords.get(0))||email.contains(specialWords.get(1))){
return false;
}
return true;
}