import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class StringUtilsTest {
@Test
public void testDataToMap() {
String data = "certificatetype=0&certificateno=220182&depositacct=622848";
Map map = new HashMap();
if (null != data) {
String[] param = data.split("&");
for (int i = 0; i < param.length; i++) {
int index = param[i].indexOf('=');
map.put(param[i].substring(0,index), param[i].substring((index + 1)));
}
}
System.out.println(map);
System.out.println("----------------分割线---------------");
Map result = new HashMap();
String[] params = data.split("\\&");
for (String entry : params) {
if (entry.contains("=")) {
String[] sub = entry.split("\\=");
if (sub.length > 1) {
result.put(sub[0], sub[1]);
} else {
result.put(sub[0], "");
}
}
}
System.out.println(result);
}
}
字符串转为Map类型:split()方法的应用
最新推荐文章于 2025-10-15 09:58:47 发布
本文介绍了一种将特定格式的字符串转换为Java中Map对象的方法。通过使用split方法结合for循环,可以有效地解析字符串并将其内容填充到Map中。本文提供了两种实现方式,并附带示例代码。
8913

被折叠的 条评论
为什么被折叠?



