"concatenating elements in an array to a string" Code Answer


use stringbuilder instead of stringbuffer, because it is faster than stringbuffer.

sample code

string[] strarr = {"1", "2", "3"};
stringbuilder strbuilder = new stringbuilder();
for (int i = 0; i < strarr.length; i++) {
string newstring = strbuilder.tostring();

here's why this is a better solution to using string concatenation: when you concatenate 2 strings, a new string object is created and character by character copy is performed.
effectively meaning that the code complexity would be the order of the squared of the size of your array!

(1+2+3+ ... n which is the number of characters copied per iteration). stringbuilder would do the 'copying to a string' only once in this case reducing the complexity to o(n).

By Hans Vonn on January 1 2022

Answers related to “concatenating elements in an array to a string”

Only authorized users can answer the Search term. Please sign in first, or register a free account.