2

Here is my String:

&username=john&password=12345&email=john@go.com

What is the best and most efficient way to break this down into key/value strings so that they can be added as params. Here's a mock example of what I need:

for (set in array)
{
   params.add(new BasicNameValuePair(set.key, set.value));
}
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194
  • 3
    Where did those strings come from? Are they *actually* part of a query string? If so, you should use something which understands query strings (performing all appropriate unescaping etc). – Jon Skeet Jul 18 '12 at 19:12
  • It looks suspiciously like a Query String. –  Jul 18 '12 at 19:14
  • Yes, it's a query string from a 3rd party source. Is there some special way to break those down? – Ethan Allen Jul 18 '12 at 19:15

5 Answers5

2

Do this:

String all = "&username=john&password=12345&email=john@go.com";
//Split across all instances of the 'and' symbol
String[] keyValueConcat = all.split("&");
Map<String, String> kvPairs = new HashMap<String, String>();
for (String concat : keyValueConcat) {
    if (concat.contains("=") {
        //For any string in the split that contains an equals sign
        //Split over the equals sign and add to the map
        String[] keyValueSplit = concat.split("=", 2);
        kvPairs.put(keyValueSplit[0], keyValueSplit[1];
    }
}

And the map kvPairs should contain what you need.

Sam Stern
  • 24,624
  • 13
  • 93
  • 124
0

You can use either StringTokenizer (or) String.split for this purpose.

kosa
  • 65,990
  • 13
  • 130
  • 167
0
String exp="&username=john&password=12345&email=john@go.com"
String[] pairs=exp.split("&");
String[] temp;
Map<String, String> myMap= new HashMap<String, String>();

for(i=0;i<pairs.length;i++){
temp=pairs[i].split("=");
myMap.put(temp[0],temp[1]);

}
Vinay W
  • 9,912
  • 8
  • 41
  • 47
0

Not sure if it is available in java for android but in Java 8 a string can be broken into key value pair using below:

String string = "&username=john&password=12345&email=john@go.com";
Map<String, String> map= Stream.of(string.split("&")).map(p->p.split("=")).filter(p->p!=null && p.length==2).collect(Collectors.toMap(p->p[0], p->p[1]));
Vinod
  • 1,076
  • 2
  • 16
  • 33