jacky jacky - 3 months ago 8
Java Question

Getting substring from String in java

I have a string that contains data with different values, something like

String values = "firstname=john&lastname=fob&email=something@something.com&Telephone=3874813781"


FYI:
&
is the separator.

I want to make a new string for all these parameters - firstname, lastname, email and etc... - and I want the string to contain only the value of it specific parameter something like

String firstname = "john";


and same for
lastname
and so on. I think it is not better to use

String firstname = values.indexOf(10);


because I don't know how many characters would the username contain so I could go for lastname an so, I was wondering if there is a better way for getting the values of each parameter and assign it to a new string.

Answer

You can use split method. Use values.split("&") , this will return you an array of Strings.

String values = "firstname=john&lastname=fob&email=something@something.com&Telephone=3874813781";
String[] parameters = values.split("&");
System.out.println(parameters[0]); // Prints firstname=john