首页 > 编程 > Java > 正文

Java 字符串从后往前每隔三位添加逗号

2019-11-06 07:11:02
字体:
来源:转载
供稿:网友

最近做一道题需要对字符串进行操作,从后往前每隔三位添加逗号,实现类似123,353,567这样的数字记法,主要用了StringBuilder类的insert方法,这个方法原型: 这里写图片描述 比如字符串s=”12345”, 则调用s.insert(2, ‘,’)会使字符串会在对应位置的前面加上‘,’。

下面上写的程序:

public static void main(String[] args) { // 创建一个空的StringBuilder对象 StringBuilder str = new StringBuilder(); // 追加字符串 str.append("jjjaewkjldfxmopzdm"); // 从后往前每隔三位插入逗号 int last = str.length(); for(int i = last - 3; i > 0; i-=3) { str.insert(i,','); } // 将StringBuilder对象转换为String对象并输出 System.out.PRint(str.toString()); }

输出结果 值得注意的一点是,在for循环的设置里头不应该设置i>=0,否则,当字符串长度是3的倍数时,会在字符串首位字符的前面多插入一个逗号。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表