I would use split
我会用Split
String text = "A=B&C=D&E=F";
Map<String, String> map = new LinkedHashMap<String, String>();
for(String keyValue : text.split(" *& *")) {
String[] pairs = keyValue.split(" *= *", 2);
map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}
EDIT allows for padded spaces and a value with an =
or no value. e.g.
编辑允许填充空格和带=或不带值的值。例如:
A = minus- & C=equals= & E==F
just use guava Splitter
只要用番石榴分离器就可以了
String src="A=B&C=D&E=F";
Map map= Splitter.on('&').withKeyValueSeparator('=').split(src);
public class TestMapParser {
@Test
public void testParsing() {
Map<String, String> map = parseMap("A=B&C=D&E=F");
Assert.assertTrue("contains key", map.containsKey("A"));
Assert.assertEquals("contains value", "B", map.get("A"));
Assert.assertTrue("contains key", map.containsKey("C"));
Assert.assertEquals("contains value", "D", map.get("C"));
Assert.assertTrue("contains key", map.containsKey("E"));
Assert.assertEquals("contains value", "F", map.get("E"));
}
private Map<String, String> parseMap(final String input) {
final Map<String, String> map = new HashMap<String, String>();
for (String pair : input.split("&")) {
String[] kv = pair.split("=");
map.put(kv[0], kv[1]);
}
return map;
}
}
String t = A=B&C=D&E=F;
Map map = new HashMap();
String[] pairs = t.split("&");
//TODO 1) Learn generis 2) Use gnerics
for (String pair : pairs)
{
String[] kv = pair.split("=");
map.put(kv[0], kv[1]);
}
Split the string (either using a StringTokenizer
or String.split()
) on '&'. On each token just split again on '='. Use the first part as the key and the second part as the value.
拆分‘&’上的字符串(使用StringTokenizer或String.Split())。在每个令牌上,只需在‘=’上再次拆分。使用第一部分作为关键字,使用第二部分作为值。
It can also be done using a regex, but the problem is really simple enough for StringTokenizer
.
这也可以使用正则表达式来完成,但是这个问题对于StringTokenizer来说真的很简单。
Using the stream api it can be done in just one sentence.
使用流API,只需一句话就可以完成。
String t = "A=B&C=D&E=F";
Map<String, String> map = Arrays.stream(t.split("&"))
.map(kv -> kv.split("="))
.collect(Collectors.toMap(kv -> kv[0], kv -> kv[1]));
更多回答
+1. In process of writing identical code. Depends partly on how much error checking the code needs to do. Is this toy code? Does this need to copy with badly formed input etc? Code here will give arrayIndexException if there is no '=' for example, but that may be just fine in the scenario.
+1.在编写相同代码的过程中。部分取决于代码需要执行多少错误检查。这是玩具密码吗?这是否需要复制格式不正确的输入等?例如,如果没有‘=’,这里的代码将给出arrayIndexException,但在这个场景中这可能是很好的。
It will handle an =
in the value rather than chopping it off ;)
它将处理值中的an=,而不是将其截断;)
我是一名优秀的程序员,十分优秀!