[英]How to recurse a String to validate that it contains only numbers after the first character
I need to create a recursive method that takes a String parameter. 我需要创建一个采用String参数的递归方法 。
I need to verify that the first letter in the string is a lowercase character, and then verify that everything that comes after the first letter is a number. 我需要验证字符串中的第一个字母是小写字符,然后验证第一个字母之后的所有内容都是数字。
So it should be like this a1234
. 所以应该像这样a1234
。
I've tried creating a base case, smaller base case, and a general case, but can't seem to figure out the right way to style it: 我尝试创建一个基本案例,一个较小的基本案例和一个一般案例,但似乎无法找出正确的样式设置方式:
public void digitCheck(String s) {
if () //To Check that first character is a letter
else if ()To check that everything after the first letter is a number
else //Invalid
}
I need the code to report whether it's a valid string if the first character is a lower case letter and everything after that is a number . 如果第一个字符是小写字母 ,之后的所有字符都是数字 ,则我需要代码来报告它是否为有效字符串。
Example: 例:
a123
-> valid . a123
> 有效 。
ab123
-> invalid . ab123
> 无效 。
使用String.matches()方法:
boolean valid = s.matches(".\\d+");
For solving this problem with recursion for your pattern you can do: 为了为您的模式递归解决此问题,您可以执行以下操作:
It should be checking until one element will be passed to the method -> make final validation if it is a lower letter. 应该检查直到将一个元素传递给方法->如果它是一个小写字母,则进行最终验证。
Also, StringUtils class is used from commons lang library. 此外, StringUtils的类是从使用公地郎库。
Here is code snippet: 这是代码片段:
public class StringValidationDemo {
public boolean validateStringRecursive(String str) {
if (str.length() == 1) {
return StringUtils.isAlpha(str) && StringUtils.isAllLowerCase(str);
}
String lastIndex = str.substring(str.length() - 1);
return StringUtils.isNumeric(lastIndex)
&& validateStringRecursive(str.substring(0, str.length() - 1));
}
public static void main(String[] args) {
List<String> words = Arrays.asList("a123", "ab123", "123ab", "A123", "aaa", "123");
StringValidationDemo demo = new StringValidationDemo();
for (String word : words) {
System.out.printf("validation for: %s = %s\n",
word, demo.validateStringRecursive(word));
}
}
}
Output: 输出:
validation for: a123 = true
validation for: ab123 = false
validation for: 123ab = false
validation for: A123 = false
validation for: aaa = false
validation for: 123 = false
I think you could ommit the first character in the string, and then just check with Integer.parseInt(String). 我认为您可以省略字符串中的第一个字符,然后仅检查Integer.parseInt(String)。 so it would look something like: 所以看起来像这样:
public static boolean isNumeric(String strNum) {
try {
double d = Integer.parseInt(String);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
public void DoStuff(String string){
if (isNumeratic(string.substring(1)) //ommits first
{
///yourstuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.