public class StringBuilterTest { public static void main(String[] args) { //新增一个map Map<String, String> map = new HashMap<>(); map.put("code", "500"); map.put("name", "测试"); map.put("age", "100"); //遍历map拼接字符串 StringBuilder stringBuilder = new StringBuilder(); for (String key : map.keySet()){ stringBuilder.append(key).append("=").append(map.get(key)).append("&"); } //这时我们往往想去除最后一个&符号,方法如下:测试的时候要分开测试这2种方法;我采用了方法1 System.out.println(stringBuilder.deleteCharAt(stringBuilder.length()-1).toString());//方法1(先删除然后转string,采用这个),结果:code=500&name=测试&age=100 System.out.println(stringBuilder.substring(0, stringBuilder.length()-1));//方法2(复制的方法,可能效率低),结果:code=500&name=测试&age=100 } }
2020-03-14 更新,方法3推荐(有一个lastINdexOf 经过测试 果然与我想的一样,推荐这个方法 效率最高,简单):
Set<String> set = new HashSet<>(); set.add("a"); set.add("b"); set.add("c"); StringBuilder stringBuilder = new StringBuilder(); for (String key: set) { stringBuilder.append(key).append(","); } System.out.println(stringBuilder.toString()); System.out.println(stringBuilder.lastIndexOf(",")); stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")); System.out.println(stringBuilder.toString());