Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete one part of the String

Tags:

java

string

get

I have this String :

String myStr = "[email protected]"

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

like image 376
Wassim AZIRAR Avatar asked Dec 03 '22 07:12

Wassim AZIRAR


2 Answers

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);
like image 92
Jon Skeet Avatar answered Dec 06 '22 10:12

Jon Skeet


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

like image 42
Ankur Avatar answered Dec 06 '22 09:12

Ankur