This is quite easy to o actually. Requirement #1 and #3 are the easiest. To test for whether a string contains two words and are separated by exactly one space, just use the split
method. For requirement #2, test if the strings have a length that is larger than 2.
Let’s say your string to test is called str
\
String str = "Jon Skeet";
You can create boolean variables to store the results of each test. It’s easier to understand.
String[] splitString = str.split(" ");
boolean test1 = splitString.length == 2;
boolean test2 = true;
for (String s : splitString) {
if s.length() < 2 {
test2 = false;
}
}
As you can see, I actually combined the word count test and the “separated by one space” test into one. Because they can be tested simultaneously using one method.
Now you have test1
and test2
. You just need to see if they are all true
:
if (test1 && test2) {
System.out.println("THE STRING IS VALID!");
}
You can even extract this as a method:
public static boolean isStringValid(String str) {
String[] splitString = str.split(" ");
boolean test1 = splitString.length == 2;
boolean test2 = true;
for (String s : splitString) {
if s.length() < 2 {
test2 = false;
}
}
if (test1 && test2) {
return true;
}
return false;
}
or you can do the test all in one go, although this is quite hard for people to understand what you are doing.
boolean test = splitString.length > 2 && splitString[0].length() >= 2 && splitString[0].length() >= 2;
EDIT:
If you want to see if it only contains letters, call Character.isLetter
.
boolean test2 = true;
boolean test3 = true;
for (String s : splitString) {
for (int i = 0 ; i < s.length() ; i++) {
if (!Character.isLetter(s.charAt(i))) {
test3 = false;
}
}
if (s.length() < 2 && ) {
test2 = false;
break;
}
}
5
solved Simplest way to validate string (Java) [closed]