C# Convert String Array to String

This C# program converts a string array into a single string.
Convert array, string. A string array can be converted into a string. This helps store many values in a single database field. There are several ways of combining the array of strings. One way uses the string.Join method. Other ways use iteration in a loop.Strings
Example. This example program has an array of 5 strings. It defines two methods that will convert that string array into a single string. In some cases, the first method is best, as it lets you check the strings before adding them together.Array

Main: It initializes a string array with five values. It then calls the two Conversion methods defined later in the program.

ConvertStringArrayToString: This uses an internal StringBuilder to convert the array to a string.

And: This technique is ideal when you need to loop over your string array before adding the elements. You can test each individual string.

Join: This version uses the string.Join method to convert the array to a string. This can be faster than StringBuilder. It is shorter code.

C# program that converts string arrays using System; using System.Text; class Program { static void Main() { // Create an array with five strings. string[] array = new string[5]; array[0] = "carrot"; array[1] = "cucumber"; array[2] = "radish"; array[3] = "beet"; array[4] = "potato"; // Call the methods. string result1 = ConvertStringArrayToString(array); string result2 = ConvertStringArrayToStringJoin(array); // Display the results. Console.WriteLine(result1); Console.WriteLine(result2); } static string ConvertStringArrayToString(string[] array) { // Concatenate all the elements into a StringBuilder. StringBuilder builder = new StringBuilder(); foreach (string value in array) { builder.Append(value); builder.Append('.'); } return builder.ToString(); } static string ConvertStringArrayToStringJoin(string[] array) { // Use string Join to concatenate the string elements. string result = string.Join(".", array); return result; } } Output carrot.cucumber.radish.beet.potato. carrot.cucumber.radish.beet.potato
Static. The two Convert methods shown are static—they do not save state. For this reason, you can place them in a static class. If you specify the separator in your code, they probably will be program-specific, which limits their reusability.JoinStatic
Summary. We converted string arrays into strings. You can use the StringBuilder class or the static string.Join method. We noted many other common tasks and solutions with converting strings, string arrays and char arrays.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls