字符串str="1,2,3,4,5,6,7,8,9,10,11,12,13,14"
变为"1-10,11,12,13-14"

解决方案 »

  1.   

    应该是
    字符串str="2,3,4,5,6,7,8,9,11,13,14" 
    变为"2-9,11,13-14"
      

  2.   

    public class test2 { public static void main(String[] args) {
    String str = new String("1,2,3,4,5,6,7,8,9,11,13,14,1000,1001,1002,15678");
    String[] s = str.split(",");
    int[] num = new int[s.length];
    for (int i = 0; i < s.length; i++) {
    num[i] = Integer.parseInt(s[i]);
    }
    str = "";
    for (int j = 0; j <= s.length - 1; j++) {
    for (int t = s.length - 1; t >= j; t--) {
    if (t != j && (num[t] - num[j]) == (t - j)) {
    str += num[j] + "-" + num[t] + ",";
    j = t;
    } else if (t == j) {
    str += num[j] + ",";
    }
    }
    }
    str=str.substring(0,str.length()-1);
    System.out.println(str);
    }
    }
      

  3.   

    楼主好像发了两个帖子,引用public class Test { 
    public static void main(String[] args) { 
        String str = new String( 
        "1,2,3,4,5,6,7,8,9,11,13,14,1000,1001,1002,1003"); 
        String[] s = str.split(","); 
        int[] num = new int[s.length]; 
        String result = ""; 
        for (int i = 0; i < s.length; i++) { 
            num[i] = Integer.parseInt(s[i]); 
        } 
        for (int i = 0; i < num.length; i++) { 
        if (i == 0) { 
           result = "" + num[i]; 
        }else if (i == num.length - 1) { 
            if (num[i] - num[i - 1] == 1) { 
                result = result + "-" + num[i]; 
            } else { 
               result = result + "," + num[i]; 
             } 
        } else { 
              if ((num[i] - num[i - 1] == 1) && (num[i + 1] - num[i] == 1)) { 
           continue; 
       } 
       if ((num[i] - num[i - 1] == 1) && (num[i + 1] - num[i] != 1)) { 
           result = result + "-" + num[i]; 
       } 
       if ((num[i] - num[i - 1] != 1)) { 
           result = result + "," + num[i]; 
       } } } 
    System.out.println(result); 

    }
      

  4.   


        public static String cut(String str){
         int count = 0,start = 0,end = 0;
         StringBuilder sb = new StringBuilder();
        
         for (String s : str.split(",")){
         if (count > 0 && Integer.parseInt(s) == end+1){
         count++;
         end++;
         }
         else{
         if (count > 0)
         sb.append(start+"-"+end+",");
        
         start = end = Integer.parseInt(s);
         count = 1;
         }
         }
         if (count > 0)
         sb.append(start+"-"+end+",");
        
         return sb.deleteCharAt(sb.length()-1).toString();
        }