2012-01-30 41 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