2

我正在努力使用下面的基本代码,

如何防止最后一个逗号“,”附加到字符串。

    String outScopeActiveRegionCode="";

    List<String> activePersons=new ArrayList<String>();

    HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>();

    for (String person : activePersons) {

       outScopeActiveRegionCodeSet.add(person); 

    }
       Iterator itr = outScopeActiveRegionCodeSet.iterator();

             while(itr.hasNext()){
                outScopeActiveRegionCode+=itr.next();
                outScopeActiveRegionCode+=",";
             }
4

2 回答 2

6

我实际上是反过来做的,除了第一种情况外,我在所有情况下都在前面附加逗号,它更容易。

boolean isFirst = true;
while(itr.hasNext()) {
    if(isFirst) {
        isFirst = false;
    } else {
        outScopeActiveRegionCode+=",";
    }
    outScopeActiveRegionCode+=itr.next();
}

这样做的原因是检测第一种情况比检测最后一种情况要简单得多。

于 2012-07-18T15:51:12.060 回答
2

我会做:

String delimiter = "";

while(itr.hasNext()){
    outScopeActiveRegionCode += delimiter;
    outScopeActiveRegionCode += itr.next();
    delimiter = ",";
}
于 2012-07-18T15:59:42.293 回答