Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of String to a String separated by a delimiter

Tags:

string

vb.net

Whats the best way to convert a list(of string) to a string with the values seperated by a comma (,)

like image 711
spacemonkeys Avatar asked Apr 15 '09 14:04

spacemonkeys


People also ask

How do you convert a list to a comma separated string?

Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.

How do you convert a list to a comma separated string in python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].

How do I store a list of integers separated by comma entered by a user inside an array in Java?

List<String> items = Arrays. asList(commaSeparated. split(",")); That should work for you.


2 Answers

String.Join(",", myListOfStrings.ToArray())
like image 70
KevB Avatar answered Sep 30 '22 07:09

KevB


That depends on what you mean by "best". The least memory intensive is to first calculate the size of the final string, then create a StringBuilder with that capacity and add the strings to it.

The StringBuilder will create a string buffer with the correct size, and that buffer is what you get from the ToString method as a string. This means that there are no extra intermediate strings or arrays created.

// specify the separator
string separator = ", ";

// calculate the final length
int len = separator.Length * (list.Count - 1);
foreach (string s in list) len += s.Length;

// put the strings in a StringBuilder
StringBuilder builder = new StringBuilder(len);
builder.Append(list[0]);
for (int i = 1; i < list.Count; i++) {
   builder.Append(separator).Append(list[i]);
}

// get the internal buffer as a string
string result = builder.ToString();
like image 30
Guffa Avatar answered Oct 02 '22 07:10

Guffa