This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:
这可能有一个简单的答案,但我一定不能喝足够的咖啡来自己搞清楚:
If I had a comma delimited string such as:
如果我有逗号分隔的字符串,例如:
string list = "Fred,Sam,Mike,Sarah";
How would get each element and add quotes around it and stick it back in a string like this:
如何获取每个元素并在其周围添加引号并将其粘贴回如下字符串:
string newList = "'Fred','Sam','Mike','Sarah'";
I'm assuming iterating over each one would be a start, but I got stumped after that.
我假设迭代每一个都是一个开始,但我在那之后感到难过。
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++;
}
15 个解决方案
#1
75
string s = "A,B,C";
string replaced = "'"+s.Replace(",", "','")+"'";
Thanks for the comments, I had missed the external quotes.
感谢您的评论,我错过了外部报价。
Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.
当然..如果源是一个空字符串,你想要它周围的额外引号吗?如果输入是一堆空格怎么办?我的意思是,要提供100%完整的解决方案,我可能会要求提供单元测试列表,但我希望我的直觉能够回答你的核心问题。
Update: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):
更新:还提出了一个基于LINQ的替代方案(使用String.Format的额外好处,因此不必担心前导/尾随引号):
string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
#2
22
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 could use LINQ, particularly with a version of String.Join which supports IEnumerable<string>
...
或者您可以使用LINQ,尤其是支持IEnumerable
return list.Split(',').Select(x => "'" + x + "'").JoinStrings(",");
There's an implementation of JoinStrings elsewhere on SO... I'll have a look for it.
在其他地方有一个关于JoinStrings的实现...我会看看它。
EDIT: Well, there isn't quite the JoinStrings I was thinking of, so here it is:
编辑:嗯,我想的不是JoinStrings,所以这里是:
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 generic overload instead though, so you could just use:
这些天string.Join有一个泛型重载,所以你可以使用:
return string.Join(",", list.Split(',').Select(x => $"'{x}'"));
#3
17
Following Jon Skeet's example above, this is what worked for me. I already had a List<String>
variable called __messages so this is what I did:
按照Jon Skeet上面的例子,这对我有用。我已经有一个名为__messages的List
string sep = String.Join(", ", __messages.Select(x => "'" + x + "'"));
#4
16
string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";
#5
#6
2
I can't write C# code, but this simple JavaScript code is probably easy to adapt:
我不能编写C#代码,但这个简单的JavaScript代码可能很容易适应:
var s = "Fred,Sam,Mike,Sarah";
alert(s.replace(/\b/g, "'"));
It just replace bounds (start/end of string, transition from word chars non punctuation) by single quote.
它只是用单引号替换边界(字符串的开始/结束,从单词字符非标点符号的转换)。
#7
1
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);
#8
1
If you are using JSON, following function would help
如果您使用的是JSON,则以下功能会有所帮助
var string[] keys = list.Split(',');
console.log(JSON.stringify(keys));
#9
1
My Requirements:
- Separate items using commas.
- Wrap all items in list in double-quotes.
- Escape existing double-quotes in the string.
- Handle null-strings to avoid errors.
- Do not bother wrapping null-strings in double-quotes.
-
Terminate with carriage-return and line-feed.
使用回车和换行终止。
string.Join(",", lCol.Select(s => s == null ? null : ("\"" + s.Replace("\"", "\"\"") + "\""))) + "\r\n";
string.Join(“,”,lCol.Select(s => s == null?null :(“\”“+ s.Replace(”\“”,“\”\“”)+“\”“) ))+“\ r \ n”;
使用逗号分隔项目。
用双引号括住列表中的所有项目。
转义字符串中的现有双引号。
处理空字符串以避免错误。
不要在双引号中包装空字符串。
#10
0
The C# implementation of @PhiLho's JavaScript regular expression solution looks something like the following:
@ PhiLho的JavaScript正则表达式解决方案的C#实现如下所示:
Regex regex = new Regex(
@"\b",
RegexOptions.ECMAScript
| RegexOptions.Compiled
);
string list = "Fred,Sam,Mike,Sarah";
string newList = regex.Replace(list,"'");
#11
0
My "less sophisticated" approach ... I suppose it's always good practice to use a StringBuilder because the list can be very large.
我的“不太复杂”的方法......我认为使用StringBuilder总是很好的做法,因为列表可能非常大。
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);
#12
0
Are you going to be processing a lot of CSV? If so, you should also consider using a library to do this. Don't reinvent the wheel. Unfortunately I haven't found a library quite as simple as Python's CSV library, but I have seen FileHelpers (free) reviewed at MSDN Magazine and it looks pretty good. There are probably other free libraries out there as well. It all depends on how much processing you will be doing though. Often it grows and grows until you realize you would be better off using a library.
你要处理很多CSV吗?如果是这样,您还应该考虑使用库来执行此操作。不要重新发明*。不幸的是,我没有找到像Python的CSV库那么简单的库,但我在MSDN杂志上看过FileHelpers(免费),看起来还不错。那里可能还有其他免费图书馆。这一切都取决于你将要做多少处理。它经常会增长和增长,直到你意识到你最好使用图书馆。
#13
0
Here is a C# 6 solution using String Interpolation.
这是使用String Interpolation的C#6解决方案。
string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => $"'{x}'")
.ToList());
Or, if you prefer the C# 5 option with String.Format:
或者,如果您更喜欢使用String.Format的C#5选项:
string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => String.Format("'{0}'", x))
.ToList());
Using the StringSplitOptions will remove any empty values so you won't have any empty quotes, if that's something you're trying to avoid.
使用StringSplitOptions将删除所有空值,这样您就不会有任何空引号,如果这是您要避免的。
#14
0
I have found a new solution for this problem
我找到了解决这个问题的新方法
I bind a list by selected items values from the grid using linq, after that added a comma delimited string for each string collections by using String.Join() properties.
我使用linq通过网格中的选定项值绑定列表,之后使用String.Join()属性为每个字符串集合添加逗号分隔的字符串。
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'
I hope this will helpful !!!!!!
我希望这会有所帮助!!!!!!
#15
0
For people who love 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;
}
#1
75
string s = "A,B,C";
string replaced = "'"+s.Replace(",", "','")+"'";
Thanks for the comments, I had missed the external quotes.
感谢您的评论,我错过了外部报价。
Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.
当然..如果源是一个空字符串,你想要它周围的额外引号吗?如果输入是一堆空格怎么办?我的意思是,要提供100%完整的解决方案,我可能会要求提供单元测试列表,但我希望我的直觉能够回答你的核心问题。
Update: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):
更新:还提出了一个基于LINQ的替代方案(使用String.Format的额外好处,因此不必担心前导/尾随引号):
string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
#2
22
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 could use LINQ, particularly with a version of String.Join which supports IEnumerable<string>
...
或者您可以使用LINQ,尤其是支持IEnumerable
return list.Split(',').Select(x => "'" + x + "'").JoinStrings(",");
There's an implementation of JoinStrings elsewhere on SO... I'll have a look for it.
在其他地方有一个关于JoinStrings的实现...我会看看它。
EDIT: Well, there isn't quite the JoinStrings I was thinking of, so here it is:
编辑:嗯,我想的不是JoinStrings,所以这里是:
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 generic overload instead though, so you could just use:
这些天string.Join有一个泛型重载,所以你可以使用:
return string.Join(",", list.Split(',').Select(x => $"'{x}'"));
#3
17
Following Jon Skeet's example above, this is what worked for me. I already had a List<String>
variable called __messages so this is what I did:
按照Jon Skeet上面的例子,这对我有用。我已经有一个名为__messages的List
string sep = String.Join(", ", __messages.Select(x => "'" + x + "'"));
#4
16
string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";
#5
4
I think the simplest thing would be to Split
and then Join
.
我认为最简单的事情是分裂然后加入。
string nameList = "Fred,Sam,Mike,Sarah";
string[] names = nameList.Split(',');
string quotedNames = "'" + string.Join("','", names) + "'";
#6
2
I can't write C# code, but this simple JavaScript code is probably easy to adapt:
我不能编写C#代码,但这个简单的JavaScript代码可能很容易适应:
var s = "Fred,Sam,Mike,Sarah";
alert(s.replace(/\b/g, "'"));
It just replace bounds (start/end of string, transition from word chars non punctuation) by single quote.
它只是用单引号替换边界(字符串的开始/结束,从单词字符非标点符号的转换)。
#7
1
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);
#8
1
If you are using JSON, following function would help
如果您使用的是JSON,则以下功能会有所帮助
var string[] keys = list.Split(',');
console.log(JSON.stringify(keys));
#9
1
My Requirements:
- Separate items using commas.
- Wrap all items in list in double-quotes.
- Escape existing double-quotes in the string.
- Handle null-strings to avoid errors.
- Do not bother wrapping null-strings in double-quotes.
-
Terminate with carriage-return and line-feed.
使用回车和换行终止。
string.Join(",", lCol.Select(s => s == null ? null : ("\"" + s.Replace("\"", "\"\"") + "\""))) + "\r\n";
string.Join(“,”,lCol.Select(s => s == null?null :(“\”“+ s.Replace(”\“”,“\”\“”)+“\”“) ))+“\ r \ n”;
使用逗号分隔项目。
用双引号括住列表中的所有项目。
转义字符串中的现有双引号。
处理空字符串以避免错误。
不要在双引号中包装空字符串。
#10
0
The C# implementation of @PhiLho's JavaScript regular expression solution looks something like the following:
@ PhiLho的JavaScript正则表达式解决方案的C#实现如下所示:
Regex regex = new Regex(
@"\b",
RegexOptions.ECMAScript
| RegexOptions.Compiled
);
string list = "Fred,Sam,Mike,Sarah";
string newList = regex.Replace(list,"'");
#11
0
My "less sophisticated" approach ... I suppose it's always good practice to use a StringBuilder because the list can be very large.
我的“不太复杂”的方法......我认为使用StringBuilder总是很好的做法,因为列表可能非常大。
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);
#12
0
Are you going to be processing a lot of CSV? If so, you should also consider using a library to do this. Don't reinvent the wheel. Unfortunately I haven't found a library quite as simple as Python's CSV library, but I have seen FileHelpers (free) reviewed at MSDN Magazine and it looks pretty good. There are probably other free libraries out there as well. It all depends on how much processing you will be doing though. Often it grows and grows until you realize you would be better off using a library.
你要处理很多CSV吗?如果是这样,您还应该考虑使用库来执行此操作。不要重新发明*。不幸的是,我没有找到像Python的CSV库那么简单的库,但我在MSDN杂志上看过FileHelpers(免费),看起来还不错。那里可能还有其他免费图书馆。这一切都取决于你将要做多少处理。它经常会增长和增长,直到你意识到你最好使用图书馆。
#13
0
Here is a C# 6 solution using String Interpolation.
这是使用String Interpolation的C#6解决方案。
string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => $"'{x}'")
.ToList());
Or, if you prefer the C# 5 option with String.Format:
或者,如果您更喜欢使用String.Format的C#5选项:
string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => String.Format("'{0}'", x))
.ToList());
Using the StringSplitOptions will remove any empty values so you won't have any empty quotes, if that's something you're trying to avoid.
使用StringSplitOptions将删除所有空值,这样您就不会有任何空引号,如果这是您要避免的。
#14
0
I have found a new solution for this problem
我找到了解决这个问题的新方法
I bind a list by selected items values from the grid using linq, after that added a comma delimited string for each string collections by using String.Join() properties.
我使用linq通过网格中的选定项值绑定列表,之后使用String.Join()属性为每个字符串集合添加逗号分隔的字符串。
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'
I hope this will helpful !!!!!!
我希望这会有所帮助!!!!!!
#15
0
For people who love 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;
}