stringA string array can be converted into a string. We can store many values in a single string. There are several ways of combining the array of strings.
We consider conversion methods: one way uses the string.Join method—this is probably the simplest. Other ways use iteration in a loop.
Join exampleThis version uses the string.Join method to convert the array to a string. This can be faster than StringBuilder. It is shorter code.
string specified as a string literal.string.Join method. Then we print the resulting string, which has period delimiters.using System; // 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}");RESULT: orange.peach.apple
StringBuilderThis code uses a StringBuilder instance to convert the array to a string. This technique is ideal when we need to loop over a string array before adding the elements.
string in the for-loop—the loop is a good place to add some logic if needed.using System; using System.Text; // 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}");RESULT: cat.frog.bird.
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.
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.