Convert array, string. A 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.
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.
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
StringBuilder. This 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.
Info We can test each individual string in the for-loop—the loop is a good place to add some logic if needed.
Warning This code will add a delimiter at the end. The code could be modified to avoid adding the final delimiter.
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.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.