Reputation: 509
I need to test whether the string given as input is a not a whole number or contains at least five English alphabets.I know how to implement it using the loops.But I think it affects the efficiency of my code.Can you please tell me any other efficient way to do this?
For eg:
11111111 //ERROR(Whole number)
1111aa11 //ERROR(less than 5 English alphabets)
aAAAAA11 //TRUE
Upvotes: 2
Views: 2673
Reputation: 1
Put it in a boolean method first. If it returns true, it is a number, otherwise, it's valid. See example below:
public boolean validateInput(String x) {
try {
Integer.parseInt(x);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
Upvotes: 0
Reputation: 1218
This is an O(n) problem... never mind what you do you are going to have to check each char in the string to see if its a number or an alphabet char. You could accidentally turn this into a O(n^2) or a O(mn) problem if you are checking for each char against an array of known alphabet and/or numbers. But if you are just using a hashtable, or some ASCII normalization method, then this should be a O(n) solution, and can't really be made any faster. Post your code if you'd like to receive comments on its implementation efficiency.
Upvotes: 4
Reputation: 526
You should try Regular expressions, for example, to test a given string is a number, the following could work:
String t = "222x";
String pattern2 = "(\\d+)";
System.out.println(java.util.regex.Pattern.matches(pattern2, t));
Which would fail, since the string contains a 'x', remove the x and it will return true. You could try the same for the other case.
Hope this is what u are looking for.
Upvotes: 0
Reputation: 1171
As per my understandings about you question,
Are looking for to get the length of the string? Then you can use .length() of the string.
You can also check the number is a whole number using Integer.parseInt(string).
Upvotes: 0