实际上,我不确定如何表述这个算法问题。我在 android 应用程序中有切换按钮,每个按钮对应一个编号的 channel 。 channel 是 (1,n) 但切换按钮 ID 是一些未知的、不连续的(对按钮而言)整数。我需要收集 channel 号并构建命令字符串。我基于 1995 年的 Java 技能给了我这个:
String ch;
int i = 1;
for (ToggleButton toggle : toggles) {
if (toggle.isChecked()) {
ch = String.format("+%d", i+1);
channels = channels.concat(ch);
}
}
如果切换按钮 1、2、4、5、6、7、11、13、21、22、23、24、25 被选中,此代码 fragment 成功地为我提供了字符串 "+1+2 +4+5+6+7+11+13+21+22+23+24+25"
但是,我更想做的是让字符串 "+1/2, +4/7, +11, +13, +21/25"
我想知道是否有比多个 if 语句更简单的方法:
String ch;
int it = 0;
int last = 1;
for (ToggleButton toggle : toggles ) {
if (toggle.isChecked()) {
if (it == last + 1) {
// somehow continue or note that we're only adding the "/"
} else {
// If we're not the next one, then build the last string
// of "n/last" and then add ", +" to start building next string
}
}
last++;
}
这似乎有点像蛮力类型的算法,所以我不知道是否有更优雅的解决方案,Java 可能在它的技巧包中(或者,更有可能的是,我应该有)
谢谢。
最佳答案
关于java.util.BitSet
我会使用 java.util.BitSet
表示和跨度搜索算法。这是基本思想 ( see on ideone.com ):
import java.util.*;
//...
BitSet bs = new BitSet();
int[] onBits = new int[] { 1,2,4,5,6,7,11,13,21,22,23,24,25 };
for (int onBit : onBits) {
bs.set(onBit);
}
System.out.println(bs);
// {1, 2, 4, 5, 6, 7, 11, 13, 21, 22, 23, 24, 25}
StringBuilder sb = new StringBuilder();
for (int begin, end = -1; (begin = bs.nextSetBit(end + 1)) != -1; ) {
end = bs.nextClearBit(begin) - 1;
if (sb.length() > 0) sb.append(", ");
sb.append(
(begin == end)
? String.format("+%d", begin)
: String.format("+%d/%d", begin, end)
);
}
System.out.println(sb);
// +1/2, +4/7, +11, +13, +21/25
nextSetBit
和 nextClearBit
方法在查找跨度方面非常方便。
在 StringBuilder
上使用 +=/concat
而不是 String
StringBuilder
连接算法是一种标准算法。这是重构后的样子:
StringBuilder sb = new StringBuilder();
for (Element e : elements) {
if (sb.length() > 0) sb.append(SEPARATOR);
sb.append(e);
}
您应该使用 StringBuilder
或 StringBuffer
而不是 String
和 +=
/concat
用于构建长字符串。
关于java - 在 Java 中将字符串连接到 "sets",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451424/