1. 程式人生 > >將字串從右往左每3位加一個逗號

將字串從右往左每3位加一個逗號

import java.util.Scanner;

/**
 * @Description     將字串從右每3位加一個逗號
 * @Version V1.0 2018/12/12 18:48
 * @Author shysin
 **/
public class StringConvertSplit {
    public static void main(String[] args) {

        System.out.print("請輸入一串數字:");
        Scanner sc = new Scanner(System.in);
        String num = sc.next();

        
//分割字串返回一個String陣列 String[] nums = num.split(""); //計算需要新增","的數量 int a = nums.length / 3; String[] tmp = new String[nums.length+a]; //反向迴圈獲取字元 for(int i=nums.length-1,j=nums.length+a-1,s=0; i>=0&&j>=0; i--,j--){ tmp[j] = nums[i]; s
++; //如果是3位,則在下一位填一個"," if(s % 3 == 0){ tmp[j] = nums[i]; j--; tmp[j] = ","; } } //去除每3位數字前面的",",如果不加,則輸入 "123" ,將會輸出 ",123"。當然,也可以在上方程式碼判斷,不過這樣更簡單 if((tmp.length-a) % 3 == 0){ tmp[0] = ""; }
for(String x : tmp){ System.out.print(x); } } }

// 版權宣告:本文為博主原創文章,轉載請標明原文連結:http://www.cnblogs.com/shiysin/p/shiysin.html