用java格式化一个字符串每隔三位添加,号

2024-11-25 07:08:06
推荐回答(3个)
回答1:

Pattern p = Pattern.compile("(?<=\\d)(?=(\\d\\d\\d)+$)");
Matcher m = p.matcher("1234567890");
System.out.println(m.replaceAll(","));

Result:1,234,567,890

回答2:

java从控制台输入一串字符串,每隔3个字符添加一个“,”号,例如:2,222public static void main(String[] args) { BufferedReader br = new ,zreWnc

回答3:

String str = "abcdefghij";
String newstr = "";
int size = ((str.length())%3 == 0) ? ((str.length())/3):((str.length())/3 + 1);
for(int i=0;i int endIndex = (i+1)*3;
if((i+1)==size){
endIndex = str.length();
}
if(i==0){
newstr += str.substring(i,endIndex);
}else{
newstr += ","+str.substring(i*3, endIndex);
}
}
System.out.print(newstr);

输出结果为abc,def,ghi ,j