dabocaiqq
2020-10-12 09:39
采纳率: 66.6%
浏览 203

不耻下问:Java语言字符串每5个一组,中间加上逗号,怎么用简单的办法实现呢

不耻下问:Java语言字符串每5个一组,中间加上逗号,怎么用简单的办法实现呢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 已采纳

    public class test {

    public static void main(String[] args) {
        //声明一个数组
        String[] str = new String[]{"1", "2", "3", "4"};
        //创建一个StringBuffer的对象
        StringBuffer str2 = new StringBuffer();
        //循环遍历数组
        for (int i = 0; i < str.length; i++) {
            //用append()方法拼接
            str2.append(str[i] + ",");
        }
        //用substring()方法截取掉最后一个 ","
        String str3 = str2.substring(0, str2.length() - 1);
        //输出拼接好的字符串
        System.out.println(str3 + "=================");
    }
    

    }

    点赞 评论
  • 燕归来兮_ 2020-10-12 09:57
      public static void main(String[] args) {
        String str = "abcdefghijklmnopqrstuvwxyz";
        char[] chars = str.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
          builder.append(chars[i]);
          if(i % 5 == 4){
            builder.append(",");
          }
        }
        System.out.println(builder.toString());
      }
    
    点赞 评论
  • Happywzy~ 2020-10-12 11:02
        public static void main(String[] args) {
            String a = "aaaabbbbcccddddeee";
            StringBuffer buffer = new StringBuffer(a);
            // 计算插几个,
            int size = a.length() / 5;
            for (int i = 0; i < size; i++) {
                buffer.insert(5 * (i + 1) + i, ",");
            }
            System.out.println(buffer.toString());
        }
    

    转成stringbuffer再来操作是最方便的

    点赞 评论

相关推荐 更多相似问题