2012-01-30 42 views
1

我有字符串包含數字(無符號整數)的陣列,例如:表示數組(字符串[])作爲字符串CSV與用零的任意數量的填充範圍

[ 0001, 0002, 0003, 0005,0007, 0010,0011,0012,0013,0014, 0015 ] 

我想要將數組轉換爲表示字符串,表示字符串應將具有範圍表示(0000-0003)和非相鄰值的相鄰值聚合爲逗號分隔值,因此,例如上述字符串數組應該表示爲以下代表字符串:

0001-0003, 0005, 0007, 0010-0015 

什麼是最好/最簡單/更可讀的方式來做到這一點(無需編寫大量的代碼:-))?

謝謝。

+5

嗯,這聽起來像功課:) – Gus 2012-01-30 20:48:54

+0

不,我想這樣做在一個類的toString()方法,我已經實現的東西,但有大量代碼...我知道,如果有一個更好/更聰明的方法。 – aleroot 2012-01-30 20:53:20

+0

「不寫大量代碼」是什麼意思? – templatetypedef 2012-01-30 20:54:04

回答

1

如果我的理解要求正確,則下面的代碼應該爲你工作:(希望這是不是一個真正的tons of code :-)

String[] arr = new String[] {"0001", "0020", "0002", "0003", "0019", "0005", "0007", 
          "0010", "0018", "0011", "0012", "0013", "0014", "0015"}; 
Map<Integer, String> m = new TreeMap<Integer, String>(); 
for (String s : arr) 
    m.put(new Integer(s), s); 
Iterator<Entry<Integer, String>> it; 
Integer prev = -1; 
StringBuffer sb = new StringBuffer(); 
boolean isCont = false; 
for (it=m.entrySet().iterator(); it.hasNext();) { 
    Entry<Integer, String> entry = it.next(); 
    if (prev == -1) 
     sb.append(entry.getValue()); 
    else if (entry.getKey() == (prev+1)) 
     isCont = true; 
    else if (entry.getKey() > (prev+1)) { 
     if (isCont) 
      sb.append('-').append(m.get(prev)).append(", "); 
     else 
      sb.append(", "); 
     sb.append(entry.getValue()); 
     isCont = false; 
    } 
    prev = entry.getKey(); 
} 
if (isCont) 
    sb.append('-').append(m.get(prev)); 
System.out.println(sb); 

OUTPUT:

0001-0003, 0005, 0007, 0010-0015, 0018-0020 
0

我會這樣做,將每個字符串視爲自己的範圍,將相鄰的字符串聯合在一起,並專門針對單個元素自身的情況執行我的Range.toString()實現。例如:

class Range { 
    int low; 
    int high; 
    public Range(int elem) { this.low = elem; this.high = elem;} 
    private Range(int low, int high) { this.low=low; this.high=high;} 
    public Range tryMerge(Range other) { 
    if(high + 1 == other.low) { 
     return new Range(low, other.high); 
    } else { 
     return null; 
    } 
    } 
    public String toString() { 
    return (low == high) ? Integer.toString(low) : low + "-" + high; 
    } 
} 

可能還有一些涉及填充的東西。

0

這裏是我的回答,當然每個人都有不同的口味。

String[] a = { "0001", "0002", "0003", "0005", "0010" , "0011" , "0012" , "0013" , "0014", "0015", "0017" }; 

    String out = new String(); 
    String curStart = null; 
    String curEnd = null; 
    for (int i=0; i<a.length; i++) { 
     if (curStart == null) curStart = a [i]; 
     if (a.length != i+1 
      && Integer.parseInt(a[i])+1 == Integer.parseInt(a[i+1])) { 
      curEnd = a[i+1]; 
     } else { 
      if (!out.equals("")) out+=", "; 
      out+=""+curStart; 
      if (curEnd != null) out+="-"+curEnd; 
      curStart = null; 
      curEnd = null;    
     } 

    } 

    System.out.println(out); 
+0

它可以與OP未在其中一個註釋中聲明的未排序**輸​​入數組一起使用嗎? – anubhava 2012-01-31 20:21:27