我有一个String数组,其中包含用任意数量的零填充的数字(无符号整数),例如:
[ 0001, 0002, 0003, 0005,0007, 0010,0011,0012,0013,0014, 0015 ]
我想将数组转换为表示字符串,表示字符串应聚合具有范围表示(0000-0003
)的相邻值和非相邻值作为逗号分隔值,因此例如上面的字符串数组应该表示为以下表示字符串:
0001-0003, 0005, 0007, 0010-0015
最好/最简单/更易读的方法是什么(没有编写大量的代码:-))?
感谢。
答案 0 :(得分: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);
<强>输出:强>
0001-0003, 0005, 0007, 0010-0015, 0018-0020
答案 1 :(得分: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);
答案 2 :(得分:-1)
我会通过将每个字符串视为自己的范围,将相邻的字符串组合在一起,并将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;
}
}
可能还有更多内容涉及填充。