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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_42682302/article/details/100990556

1、使用subString的方法去删除

private static void method02() {  
        String[] str = { "3", "4", "5" };    
        StringBuilder sb = new StringBuilder();  
        if (str != null && str.length > 0) {  
  
            for (String s : str) {  
                sb.append(s + ",");  //循环遍历数组中元素,添加到 StringBuilder 对象中  
            }  
        }  
        if (sb.length() > 0)  
            sb.deleteCharAt(sb.length() - 1); //调用 字符串的deleteCharAt() 方法,删除最后一个多余的逗号  
        System.out.println(sb.toString());  

2、使用substring截取字符串

for (int t = 0; t < memberLen; t++) {
      memTemp =  stafferMap.get(strMember[t]);
      if(memTemp != null){
       memberNames += memTemp + ",";
      }
     }

以上的代码,拼接的字符串会多一个“,”,比如:“str1,str2,str3,”,要去除str3后的逗号,可用如下方法:

memberNames = memberNames.substring(0,memberNames.length()-1);

比如当Team1=test ', 'U1-Team ', 'V-Team ', '时

如何改成:

Team1= 'test ', 'U1-Team ', 'V-Team ’

可用:

Team1   =   " ' "   +   Team1.Substring(0,   Team1.Length   -   2);

2、

private static void method02() {  
        String[] str = { "3", "4", "5" };    
        StringBuilder sb = new StringBuilder();  
        if (str != null && str.length > 0) {  
  
            for (String s : str) {  
                sb.append(s + ",");  //循环遍历数组中元素,添加到 StringBuilder 对象中  
            }  
        }  
        if (sb.length() > 0)  
            sb.deleteCharAt(sb.length() - 1); //调用 字符串的deleteCharAt() 方法,删除最后一个多余的逗号  
        System.out.println(sb.toString());  
    } 
    ```

猜你喜欢

转载自blog.csdn.net/qq_42682302/article/details/100990556
今日推荐