0

I have a string variable with a space separating an email address and a password. For example:

one_variable="foo@yahoo.com password"

I would like to separate the email address from the password and create two strings from it, like this:

email_variable="foo@yahoo.com"
password_variable="password"

How do I achieve this?

happydude
  • 3,869
  • 2
  • 23
  • 41
Robot
  • 101
  • 4
  • 11
  • 7
    Simply split by `space` – vks Feb 10 '15 at 06:17
  • Sorry, But i don't get you .. Can you please help me? – Robot Feb 10 '15 at 06:19
  • [Read this SO thread](http://stackoverflow.com/q/3481828/3150943) – nu11p01n73R Feb 10 '15 at 06:20
  • `String parts[]=one_variable.split(" ");` and then access the array with indices to get the variables – vks Feb 10 '15 at 06:21
  • Use [`split()`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)) method of [`String`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true) class. – PM 77-1 Feb 10 '15 at 06:22

1 Answers1

2

Try following code:

String one_variable="foo@yahoo.com password";
String tok[]=one_variable.split(" ");
System.out.println(tok[0]);
System.out.println(tok[1]);

Code basically would spilt the string from space.
If in case you have multiple spaces use \\s+ to spilt i.e one_variable.split("\\s+").
Output :

foo@yahoo.com
password
Darshan Lila
  • 5,772
  • 2
  • 24
  • 34