In C #: Add quotes around a line in a comma-separated list of lines

This probably has a simple answer, but I didn't have to have enough coffee to figure it out on my own:

If I had a comma delimited string, for example:

string list = "Fred,Sam,Mike,Sarah"; 

How to get each element and add quotation marks to it and insert it into the string as follows:

 string newList = "'Fred','Sam','Mike','Sarah'"; 

I assume that iterating over each of them will be the beginning, but after that I was at an impasse.

One solution that is ugly:

 int number = 0; string newList = ""; foreach (string item in list.Split(new char[] {','})) { if (number > 0) { newList = newList + "," + "'" + item + "'"; } else { newList = "'" + item + "'"; } number++; } 
+41
string c #
Oct 31 '08 at 15:56
source share
15 answers
 string s = "A,B,C"; string replaced = "'"+s.Replace(",", "','")+"'"; 

Thanks for the comments, I missed the outer quotes.

Of course, if the source was an empty string, would you like extra quotation marks around it or not? But what if the entrance was a bunch of spaces ...? I mean, to give a 100% complete solution, I would probably ask for a list of unit tests, but I hope that my gut instinct answers your basic question.

Update: An LINQ-based alternative has also been proposed (with the added benefit of using String.Format and therefore no need to worry about leading / trailing caves):

 string list = "Fred,Sam,Mike,Sarah"; string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList()); 
+66
Oct 31 '08 at 15:57
source share
 string[] bits = list.Split(','); // Param arrays are your friend for (int i=0; i < bits.Length; i++) { bits[i] = "'" + bits[i] + "'"; } return string.Join(",", bits); 

Or you can use LINQ, especially with the version of String.Join that supports IEnumerable<string> ...

 return list.Split(',').Select(x => "'" + x + "'").JoinStrings(","); 

There is an implementation of JoinStrings elsewhere in SO ... I will look for it.

EDIT: Well, not the way I thought about concatenated strings, so here it is:

 public static string JoinStrings<T>(this IEnumerable<T> source, string separator) { StringBuilder builder = new StringBuilder(); bool first = true; foreach (T element in source) { if (first) { first = false; } else { builder.Append(separator); } builder.Append(element); } return builder.ToString(); } 

These days, string.Join has a common overload instead, so you can just use:

 return string.Join(",", list.Split(',').Select(x => $"'{x}'")); 
+20
Oct 31 '08 at 16:01
source share
 string[] splitList = list.Split(','); string newList = "'" + string.Join("','", splitList) + "'"; 
+15
Oct 31 '08 at 16:01
source share

Following the example of Jon Skeet, this is what worked for me. I already had a List<String> variable called __messages, here is what I did:

 string sep = String.Join(", ", __messages.Select(x => "'" + x + "'")); 
+14
Mar 14 '12 at 15:57
source share

I think the simplest thing would be Split and then Join .

 string nameList = "Fred,Sam,Mike,Sarah"; string[] names = nameList.Split(','); string quotedNames = "'" + string.Join("','", names) + "'"; 
+4
Oct 31 '08 at 16:02
source share

I cannot write C # code, but this simple JavaScript code is probably adaptable easily:

 var s = "Fred,Sam,Mike,Sarah"; alert(s.replace(/\b/g, "'")); 

It simply replaces the boundaries (beginning / end of the line, the transition from the word characters without punctuation), one quote.

+2
Oct 31 '08 at 16:01
source share
 string list = "Fred,Sam,Mike,Sarah"; string[] splitList = list.Split(','); for (int i = 0; i < splitList.Length; i++) splitList[i] = String.Format("'{0}'", splitList[i]); string newList = String.Join(",", splitList); 
+1
Oct 31 '08 at 16:03
source share

If you use JSON, the following function will help

 var string[] keys = list.Split(','); console.log(JSON.stringify(keys)); 
+1
Apr 17 '13 at 2:14
source share

My requirements:

  • Separate items with commas.
  • Wrap all items in the list with double quotation marks.
  • Exclude existing double quotes in a string.
  • Process null strings to avoid errors.
  • Do not bother wrapping zero strings in double quotes.
  • Finish with carriage return and line feed.

    string.Join (",", lCol.Select (s => s == null? null: ("\" "+ s.Replace (" \ "", "\" \ "") + "\")) ) + "\ r \ n";

+1
Feb 17 '15 at 20:35
source share

C # implementation for @ PhiLho JavaScript regex solution looks something like this:

 Regex regex = new Regex( @"\b", RegexOptions.ECMAScript | RegexOptions.Compiled ); string list = "Fred,Sam,Mike,Sarah"; string newList = regex.Replace(list,"'"); 
0
Oct 31 '08 at 16:17
source share

My "less complicated" approach ... I believe that it is always recommended to use StringBuilder, because the list can be very large.

 string list = "Fred,Sam,Mike,Sarah"; StringBuilder sb = new StringBuilder(); string[] listArray = list.Split(new char[] { ',' }); for (int i = 0; i < listArray.Length; i++) { sb.Append("'").Append(listArray[i]).Append("'"); if (i != (listArray.Length - 1)) sb.Append(","); } string newList = sb.ToString(); Console.WriteLine(newList); 
0
Oct. 31 '08 at 16:44
source share

Are you going to handle a lot of CSV? If so, you should also consider using a library for this. Do not reinvent the wheel. Unfortunately, I did not find the library as simple as the Python CSV library, but I saw FileHelpers (for free) reviewed in the MSDN journal , and it looks pretty good. There are probably other free libraries. It all depends on how much processing you will do. Often it grows and grows until you realize that you are better off using the library.

0
Oct 31 '08 at 18:56
source share

Here is a C # 6 solution using String Interpolation.

 string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => $"'{x}'") .ToList()); 

Or, if you prefer the C # 5 option using String.Format:

 string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => String.Format("'{0}'", x)) .ToList()); 

Using StringSplitOptions will remove any empty values, so you will not have empty quotes if that is what you are trying to avoid.

0
Dec 15 '15 at 16:34
source share

I found a new solution to this problem

I bind the list according to the selected values โ€‹โ€‹of the elements from the grid using linq, then add a comma-separated string for each collection of strings using the String.Join () properties.

 String str1 = String.Empty; String str2 = String.Empty; //str1 = String.Join(",", values); if you use this method,result "X,Y,Z" str1 =String.Join("'" + "," + "'", values); //The result of str1 is "X','Y','Z" str2 = str1.Insert(0, "'").Insert(str1.Length+1, "'"); //The result of str2 is 'X','Y','Z' 

Hope this helps !!!!!!

0
Jun 15 '16 at 6:10
source share

For people who like extension methods like me, here it is:

  public static string MethodA(this string[] array, string seperatedCharecter = "|") { return array.Any() ? string.Join(seperatedCharecter, array) : string.Empty; } public static string MethodB(this string[] array, string seperatedChar = "|") { return array.Any() ? MethodA(array.Select(x => $"'{x}'").ToArray(), seperatedChar) : string.Empty; } 
0
Sep 01 '16 at
source share



All Articles