拼接字符串时,去掉最后一个多余的逗号

1. 概述

有时候在调用服务器接口时,需要给服务器传递的参数是需要客户端进行拼接字符串的:

比如在自己项目中的 我的收藏列表中,删除收藏的商品时候,可以删除单个或者多个,这个时候就需要给服务器传递 merchantIds:
如果删除一个商品,就传递这个商品的merchantId;
如果删除多个商品,就需要拼接多个商品的merchantId;
如下图所示:


图片.png
2. 实现方案如下

第一步:首先定义一个临时集合tempDeletelist ,用于将选中的商品的实体类对象添加到tempDeletelist 中;
第二步:遍历 tempDeletelist 集合, 取出每一个 id ;
第三步:然后拼接 merchantIds ;

private String merchantIds="";
if (tempDeletelist != null && tempDeletelist.size() > 0){

     // 这里一定要注意:在任何需要拼接字符串之前的地方,一定要 merchantIds = "",
     // 否则拼接的merchantIds字符串就会错乱、重复,这里一定要注意 !!!
     merchantIds = "" ;
     for (int i = 0; i < tempDeletelist.size(); i++) {
          String id = tempDeletelist.get(i).getMerchantId()+"";
          merchantIds += id ;
          merchantIds += "," ;
     }
     if (merchantIds.endsWith(",")){
           merchantIds = merchantIds.substring(0,merchantIds.length()-1) ;
     }
// 然后把 拼接的 merchantIds传递给 服务器即可
doDeleteProduct(merchantIds,tempDeletelist) ;

你可能感兴趣的:(拼接字符串时,去掉最后一个多余的逗号)