一个验证字符串的方法

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

/**
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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值