一个验证字符串的方法

自己写的一个验证字符串的类

/**
Validate a String such that it meets the following rules:
4 Rules:
Rule1: the length of the string should be between 5 and 15(inclusive);
Rule2: at least a digit should be contained within the string;
Rule3: all the characters should be in lower case;
Rule4: there are no adjacent identical substrings, eg, banana123, violates rule4, because b[an][an]123, while b[an]c[an]123 is a valid one.
*/
public class StringValidation
{
public static void main(String[] args) {
String test1 = "bancanab2324";
String test2 = "bananab2324";
validateStr(test1);
validateStr(test2);
}

public static boolean validateStr(String aStr) {
if(aStr.length() < 5 && aStr.length() > 15) {//rule1
System.out.println(" The length is : " + aStr.length());
return false;
}
//Check if there is any digit in the string
char zero = '0';
char nine = '9';
boolean hasDigit = false;
for(int i = 0; i < aStr.length(); i++ ) {
if(aStr.charAt(i) >= zero && aStr.charAt(i) <= nine) {
hasDigit = true;
break;
}
}
if(!hasDigit) {//no digit in the string.
System.out.println("There are no digits contained in the string!");
return false;
}

//Rule3
if(!aStr.equals(aStr.toLowerCase())){
System.out.println("The characters in the string are not all in lower case!");
return false;
}

String subStr1 = null;
String subStr2 = null;
int span = 0;//the length of the substring.
//Rule4
for(int i = 0; i < aStr.length() - 1; i++){
//we don't have to traverse the rest of the string, because the substring's length won't surpass half of the rest string.
for(int j = i + 1; j <= i + (aStr.length() - i) / 2; j++ ) {
subStr1 = aStr.substring(i, j);
span = j - i;
subStr2 = aStr.substring(j, j + span);
System.out.println(subStr1 + " : " + subStr2);
if(subStr1.equals(subStr2)) {
System.out.println("There exist two identical adjacent substrings!");
return false;
}
}//inner for
}//outer for

return true;
}
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页