This is most common situation we encounter, joining an array (list) of string into a delimiter seperarted string (most commonly comma seperated). We use string builder to append the array items and make it as one string using a foreach loop.
string[] stringArray = new string[] { "This", "is", "single", "string" };
_______________________________________
Stringbuilder way
StringBuilder sbObject = new StringBuilder();
foreach (string strItem in stringArray)
sbObject.Append(strItem + " ");
string finalString = sbObject.ToString();
//remove the last character
finalString = finalString.Substring(0, finalString.Length);
output for this code is
"This is single string"
________________________________________
Instead of the above code we can use string.Join(), a built in method which is much efficient and reduces coding effort significantly.
string finalString = string.Join(" ", stringArray);
--
happy coding
No comments:
Post a Comment