Reputation: 67
I need to find a way to search the email and find out if the email field in an array is missing "@", "." or has a blank space.
So far I've found http://www.tutorialspoint.com/java/util/arraylist_contains.htm , and http://www.tutorialspoint.com/java/lang/string_contains.htm . Which is good but still confuses me.
I have a get method for the email (getEmail) and Im trying to figure out how it would loop through the myRoster array and print out each email missing that information. Any clarification or help would be appreciated.
Upvotes: 0
Views: 70
Reputation: 11483
A previous poster pointed out using "boolean flags" while iterating the String. This is okay if you're doing some microscopic performance optimizations, but I think it's a bit of an overoptimization compared to using some simpler methods like String#indexOf
.
public boolean hasValidEmail(String email) {
int at = email.indexOf('@');
//first ensures '@' exists, then that '.' is after '@', and lastly checks for no space
return at > 0 && email.lastIndexOf('.') > at && !email.contains(' ');
}
It's definitely not perfect, and there are attempts at regex validations for such things out there, but for a simple check it's more than sufficient.
If you really did want to do the string iteration only once, you could iterate #toCharArray
. Though I'd recommend just using direct char comparison over #compareTo
:
char c = /* some char */;
if (c == '@') {
//etc
}
In short, "premature optimization is the root of all evil". It's certainly fine to optimize but there are better, more modern methods like profiling of finding out why code is slow.
Upvotes: 3
Reputation: 848
Loop through the email string with boolean flags set to false for each character you are looking for. If you find the character you are searching for set the flag to true. At the end of the loop if the flag is still false the character wasn't found.
For example..
Boolean atFound = false;
Boolean periodFound = false;
Boolean spaceFound = false;
For (integer cnt = 0; cnt < email.length; cnt ++)
{
If (email [cnt].compareTo ("@") == 0)
atFound = true;
If (email [cnt].compareTo (".") == 0)
periodFound = true;
If (email [cnt].compareTo (" ") == 0)
spaceFound = true;
}
Upvotes: 0