有没有什么办法能够按位数分割字符串?
如我有个字符串“1234234234235”,这个字符串不是定长的(或多或少)
怎样让他每隔3个用个“,”分割?

解决方案 »

  1.   

    使用的是VC++6.0
    方法一
    1. CString str = "1234234234235";
       CString newStr,strTemp;
    2. int num = atoi(str);
    3. int i,j,k;
    4. 
    i=1000
    while(num/i>0)
    {
      strTemp.Format(",%d",num%i);
      i = i * 1000;
    }
      

  2.   


    public String splitPerLen(String source, int len, String sign) {
        
        String target = "";
        if (null == source || "" == source) {
            return "";
        } else if (len <= 0 || source.length() < len){
            return source;
        } else {
            int num = source.length()/len;
            for (int i=0; i < num; i++) {
                target += source.substring(i*len, (i+1)*len) + sign;
            }
            target += source.substring(num*len);
        }
        return target.trim();
    }len:是要指定长度;
    sign:指定插入的记号。但是用StringBuffer可能有更好的办法。
      

  3.   

        public static void main(String[] args) throws Exception {
         StringBuffer sb = new StringBuffer("1234234234235");
         int count = sb.length() / 3;
         for (int i = 0; i < count; i++) {
         sb.insert((i+1)*3+i, ',');
         System.out.println (sb);
         }
         System.out.println (sb);
        }
      

  4.   


    String str="12312312312311";
    NumberFormat nf=new DecimalFormat(",###");
    System.out.println(nf.format(new BigDecimal(str)));
      

  5.   

         StringBuffer sb = new StringBuffer("1234234234235");
         int count = sb.length() / 3;
         for (int i = 0; i < count; i++)
         sb.insert((i+1)*3+i, ',');只要这4句就可以
      

  6.   

    /**
     * 把数字格式转换为,分式
     * @param number
     * @return
     */
    public static String numberFormat(double number){
    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(number);
    }
      

  7.   

    public static void main(String []args)
    {
    String x="hjgjhgjkhgjhghj";
    String y="";
    for(int i=0; i<x.length;i++ )
    {
      y+=x.charat(i);
      int j=0;
      j++;
      if(j==3)
      j=0;y+=",";
    }
    }
      

  8.   

    感谢了各位
    我还有一种
    String demoString ="123445678,564,534,567,835,123,235,654,432";
        String repString = demoString.replaceAll(",", "");
        String studentId = repString.substring(0, 9);
        String dataItemId = repString.substring(9, repString.length());
        int dataItemIdLen = dataItemId.length()/3;
        List li = new ArrayList();
        for(int i=0; i<dataItemIdLen;i++){
         String tmp =dataItemId.substring(0, 3);
         dataItemId =dataItemId.replaceAll(tmp, "");
         System.out.println(tmp+"-----");
         System.out.println(dataItemId);呵呵