See Easy way to put a comma every 3 digits such as price notation "If you write your own comma-separated logic without using String # format or NumberFormat, how would you implement it?" I was interested in that, so I tried to implement it easily
I feel like I can get a subset of 3 digits with a regular expression and fold it with reduce. ~~ If you cut it out with tsubstring, the operation of subscripts seems to be troublesome ~~ If the number of characters is not a multiple of 3, it seems that you should forcibly enter the previous zero.
MyFormatter.java
package formatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyFormatter {
    public static void main(String[] args) throws Exception{
    	System.out.println(format("11"));
    	System.out.println(format("111"));
    	System.out.println(format("1111"));
    	System.out.println(format("11111"));
    	System.out.println(format("111111"));
    }	
    public static String format(String str) {
        Matcher matcher = Pattern.compile("(\\d{3})").matcher(makeStr(str));
        List<String> strs =new ArrayList<String>();
        //Remove the previous 0
        if(matcher.find()) {
        	strs.add(Integer.parseInt(matcher.group()) + "");
        }
        while(matcher.find()) {
        	strs.add(matcher.group());
        }
        //,It is cleaner to use reduce to add
    	return strs
    			.stream()
    			.reduce((s,s1)-> s+","+s1)
    			.get();
    	
    }
    public static String makeStr(String str) {
    	if(str.length()%3 ==2)return "0" + str;
    	else if(str.length()%3 ==1)return "00" + str;
    	else return str;
    }
}
11
111
1,111
11,111
111,111
--Java is troublesome to get a substring with a regular expression, I wish the group function returned a stream ――This logic seems to be applicable when you want to cut out a character string by XX characters.
Recommended Posts