Home
C#
Convert String Array to String
This page was last reviewed on Oct 11, 2023.
Dot Net Perls
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.
Shows a string arrayShows an array
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.
string.Join
Part 2 We invoke the string.Join method. Then we print the resulting string, which has period delimiters.
Shows a string array
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.
Shows an array
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.
Array
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.