Let's say I have an email address. Like: [email protected].
And I need to break it apart without using split or loops. And that I need to use IndexOf
in combination with substring and not using a loop (this will come later after I have a strong understanding of this first).
But looking at this email address with the understanding the email addresses are formatted like: (firstName + "." + lastName + "@" + companyName + ".com")
emailAddress = input.nextLine();
// This is where I have issues.
firstName = emailAddress.substring(emailAddress.IndexOf(".") );
// How do I get this to be just the last name and not lastName + "@somecompany.com"
lastName = emailAddress.substring(emailAddress.IndexOf(".") + 1);
// And how do I get the company name without the ".com"
companyName = emailAddress.substring(emailAddress.IndexOf("@") + 1);
Thank you for any help you can provide. I can see how this would be very helpful and would like to learn.
I have looked through and I have not seen a response to my question.
Here is how you would do it in this scenario:
String emailAddress = "[email protected]";
String firstName = emailAddress.substring(0, emailAddress.indexOf('.'));
String lastName = emailAddress.substring(emailAddress.indexOf('.') + 1, emailAddress.indexOf('@'));
String companyName = emailAddress.substring(emailAddress.indexOf('@') + 1, emailAddress.lastIndexOf('.'));
System.out.println("Firstname: " + firstName + "\nLastname: " + lastName + "\nCompany: " + companyName); //Print them
Output:
Firstname: kate
Lastname: daniels
Company: somecompany
Substring
needs two parameters to get a range, start and end index. Substring
with only a single parameter assumes the parameter is the beginning index and returns the rest of the String
starting from that location. See the documentation here.
Note that the beginning index for substring
is inclusive so for lastName
and companyName
I needed to put +1
to exclude the .
and the @
from the result.
Another important thing to note is for the emailAddress
I had to use lastIndexOf(".")
because there are two periods in the String
and this will ensure you get the final one to substring
the correct ranges. Normally indexOf
returns the first occurrence.