What's the best way to build a string of delimited items in Java?

前端 未结 30 2506
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 06:16

    //Note: if you have access to Java5+, 
    //use StringBuilder in preference to StringBuffer.  
    //All that has to be replaced is the class name.  
    //StringBuffer will work in Java 1.4, though.
    
    appendWithDelimiter( StringBuffer buffer, String addition, 
        String delimiter ) {
        if ( buffer.length() == 0) {
            buffer.append(addition);
        } else {
            buffer.append(delimiter);
            buffer.append(addition);
        }
    }
    
    
    StringBuffer parameterBuffer = new StringBuffer();
    if ( condition ) { 
        appendWithDelimiter(parameterBuffer, "elementName", "," );
    }
    if ( anotherCondition ) {
        appendWithDelimiter(parameterBuffer, "anotherElementName", "," );
    }
    
    //Finally, to return a string representation, call toString() when returning.
    return parameterBuffer.toString(); 
    

提交回复
热议问题