I have a question regarding indexOf()
. I am trying to program an EmailExtractor
(Yes, this is a homework but I am not looking for code) which extracts the entire email address from a sentence that is input by a user.
For example -
User Input: Mail us at abc@def.ghi.jk with your queries.
The program will then display abc@def.ghi.jk from the above String
. I understand indexOf()
and substring()
are required.
The idea I have now is to use indexOf()
to locate the '@', and then search for the empty space just before the email address input by the user (nth).
My code is as follows:
System.out.println("This is an Email Address Extractor.\n");
System.out.print("Enter a line of text with email address: ");
String emailInput = scn.nextLine();
int spaceAt = emailInput.indexOf(" ");
for (int i = 1; i <= emailInput.indexOf("@"); i++){
if (spaceAt < emailInput.indexOf("@")) {
spaceAt = emailInput.indexOf(" ", spaceAt + 1);
}
}
I understand and am aware of the problem in my code.
1) "Mail us at abc@def.ghi.jk with your queries".indexOf(" ")
is 4, I am trying to get 10. However, the IF Condition I have input will cause it to skip to the next instance of indexOf() which is 25. (Because 10 < 14).
How do I go about avoiding this from happening?
Once again, I am not looking for purely the answer rather, I am trying to work around a solution. Thanks in advance!