开发者

An efficient way to parse the following string?

I'm getting the following response from a server in the form of a S开发者_C百科tring...

value_one=3342342&value_two=456344445&value_three=235333223

What would be an efficient way to parse this? Everything I can come up with is pretty messy.


Split on '&', loop, split on '='

public static Map<String, String> getQueryMap(String query)
{
    String[] params = query.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String param : params)
    {
        String name = param.split("=")[0];
        String value = param.split("=")[1];
        map.put(name, value);
    }
    return map;
}


If you are planning to parse multiple strings, then repeatedly using String.split() method is not a good idea, because it would recompile split regular expression every time.

Pattern ampPattern = Pattern.compile("&");
Pattern eqPattern = Pattern.compile("=");
...

Map<String, Long> results = new HashMap<String, Long>();
for (String param : ampPattern.split(input)) {
  String[] pair = eqPattern.split(param);
  results.put(pair[0], Long.valueOf(pair[1]));
}

However for such a simple input string it will be even more efficient to not use regexps at all and avoid creation of temporary String arrays. Perhaps something like this:

Map<String, Long> results = new HashMap<String, Long>();
int start = 0;
int next;
do {
  next = input.indexOf('&', start);
  int end = next == -1 ? input.length() : next;
  int k = input.indexOf('=', start);
  results.put(input.substring(start, k), Long.valueOf(input.substring(k + 1, end)));
  start = next + 1;
} while (next > -1);

Of course, if you only parsing this string few times, such optimization may not worth it.


First split the string on a "&".This will give you tokens each consisting of a name and value pair with a "=" separating them. So split them on "=" as required. Seems very simple to me unless you have other requirements.


A naïve approach is to just use String.split:

String input = "value_one=3342342&value_two=456344445&value_three=235333223"
String[] rawAttrs = input.split("&");

// Split each attribute into pairs - assume some sort of Pair class exists
List<Pair<String, String>> attributes = new ArrayList<Pair<String, String>>();
for (String rawAttr : rawAttrs) {
    String[] parts = rawAttrs.split("=");
    attributes.add(new Pair<String, String>(parts[0], parts[1]);
}

This approach doesn't handle malformed entries well - but more importantly, it doesn't consider what happens if part of the attribute values includes an = or & character. Are these backslash-escaped? Are they URL-encoded? Is there some other way that they would be embedded?

If you can guarantee that the values are integers then this won't be a problem, but you need to ensure that all the bases are covered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜