Function: Join () function: combines an array into a string using the selected separator. This is the method provided in JavaScript. net contains a similar string. the join method can concatenate the specified separator string between each element of the specified string array to generate a single concatenation string, because most of the problems encountered are for the string array, so it is barely enough. But there is no such method in Java. Here we provide a solution.
Public static string join (Collection S, string delimiter ){
Stringbuffer buffer = new stringbuffer ();
Iterator iter = S. iterator ();
While (ITER. hasnext ()){
Buffer. append (ITER. Next ());
If (ITER. hasnext ()){
Buffer. append (delimiter );
}
}
Return buffer. tostring ();
}
If we remove the if statement from the loop, the efficiency will be improved.
Public static string join (abstractcollection S, string delimiter ){
Stringbuffer buffer = new stringbuffer ();
Iterator iter = S. iterator ();
If (ITER. hasnext ()){
Buffer. append (ITER. Next ());
While (ITER. hasnext ()){
Buffer. append (delimiter );
Buffer. append (ITER. Next ());
}
}
Return buffer. tostring ();
}
This looks more comprehensive.
Public static string join (abstractcollection <string> S, string delimiter ){
If (S. isempty () Return "";
Iterator <string> iter = S. iterator ();
Stringbuffer buffer = new stringbuffer (ITER. Next ());
While (ITER. hasnext () buffer. append (delimiter). append (ITER. Next ());
Return buffer. tostring ();
}