在 C# 中:在以逗号分隔的字符串列表中的字符串周围添加引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/254009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In C#: Add Quotes around string in a comma delimited list of strings
提问by Bob Wintemberg
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++;
}
采纳答案by FOR
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());
回答by Tor Haugen
string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";
回答by Jon Skeet
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<string>
...
return list.Split(',').Select(x => "'" + x + "'").JoinStrings(",");
There's an implementation of JoinStrings elsewhere on SO... I'll have a look for it.
在 SO 上的其他地方有一个 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}'"));
回答by PhiLho
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.
它只是用单引号替换边界(字符串的开始/结束,从单词字符非标点符号的转换)。
回答by Jacob Carpenter
回答by RickL
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);
回答by bdukes
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,"'");
回答by bruno conde
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);
回答by Ryan
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 Magazineand 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(免费),它看起来很不错。可能还有其他免费图书馆。不过,这一切都取决于您将进行多少处理。通常它会不断增长,直到您意识到使用库会更好。
回答by vcuankit
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 的例子,这对我有用。我已经有一个List<String>
名为 __messages的变量,所以这就是我所做的:
string sep = String.Join(", ", __messages.Select(x => "'" + x + "'"));