C# Convert String Array to String

Convert a string array into a single string, using the string.Join method and StringBuilder.

dot net perls

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.

Methods used. We consider conversion methods: one way uses the string.Join method—this is probably the simplest. Other ways use iteration in a loop.

Join example. This version uses the string.Join method to convert the array to a string. This can be faster than StringBuilder. It is shorter code.
Part 1: We create an array with 3 elements—each element is a string specified as a string literal.
Part 2: We invoke the string.Join method. Then we print the resulting string, which has period delimiters.
C# program that converts string array to string using System; class Program { static void Main() { // Part 1: create an array. string[] array = new string[3]; array[0] = "orange"; array[1] = "peach"; array[2] = "apple"; // Part 2: call string.Join. string result = string.Join(".", array); Console.WriteLine($"RESULT: {result}"); } } Output RESULT: orange.peach.apple

StringBuilder. This code uses a StringBuilder instance to convert the array to a string. This technique is ideal when you need to loop over your string array before adding the elements.StringBuilder
Also: You can test each individual string. This is a good place to add some logic if needed.
C# program that converts string array with StringBuilder using System; using System.Text; class Program { static void Main() { // Create an array. string[] array = new string[] { "cat", "frog", "bird" }; // Concatenate all the elements into a StringBuilder. StringBuilder builder = new StringBuilder(); foreach (string value in array) { builder.Append(value); builder.Append('.'); } string result = builder.ToString(); Console.WriteLine($"RESULT: {result}"); } } Output RESULT: cat.frog.bird.

Notes, method usage. If string.Join fits our requirements, it is the best choice. But if we have more complex needs, using StringBuilder may be better, as it gives us more control.

A summary. We converted string arrays into strings. We can use StringBuilder or the string.Join method. We noted many other common tasks and solutions with converting strings.Array


© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.