4

I have this String :

String myStr = "[email protected]"

I want to get just the "something.bad" from myStr ?

5
  • will it always be an email adress and you want what's before the @ or is it just a substring you need? Commented Aug 11, 2011 at 13:06
  • It will be always email format Commented Aug 11, 2011 at 13:07
  • Then Jon Skeet's is the answer Commented Aug 11, 2011 at 13:07
  • 1
    Uhm...there's a String API, you know? Commented Aug 11, 2011 at 13:11
  • @talnicolas of course jon skeets answer is the answer :P Commented Aug 11, 2011 at 13:15

2 Answers 2

12

You just need to use substring having found the right index to chop at:

int index = myStr.indexOf('@');
// TODO: work out what to do if index == -1

String firstPart = myStr.substring(0, index);

EDIT: Fairly obviously, the above takes the substring before the first @. If you want the substring before the last @ you would write:

int index = myStr.lastIndexOf('@');
// TODO: work out what to do if index == -1

String firstPart = myStr.substring(0, index);
Sign up to request clarification or add additional context in comments.

6 Comments

Actually since we're talking about email - and as we all know legal email addresses may actually contain @s - one should really use lastIndexOf. Not that anyone would ever use such an email address, because pretty much every website ever contains code such as the above, so it probably won't matter in reality ;)
@Voo: Well, we don't really know the details of what the OP wants. Maybe, maybe not.
He said in a comment to his original post that it will always be email format.
@Voo: Yes, but not what he wanted to use the result for.
I just assumed he wanted to get rid of the domain and it's an easy to make assumption that no local-part may ever contain an @. But you could be right - he would have to clarify a bit.
|
5

You can use

String str = myStr.split("@")[0];

It will split the string in two parts and then you can get the first String element

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.