gpt4 book ai didi

c# - 在 C# : Add Quotes around string in a comma delimited list of strings 中

转载 作者:IT王子 更新时间:2023-10-29 03:49:11 24 4
gpt4 key购买 nike

这可能有一个简单的答案,但我肯定没有喝足够的咖啡来自己弄清楚:

如果我有一个逗号分隔的字符串,例如:

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

如何获取每个元素并在其周围添加引号并将其粘贴回像这样的字符串中:

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

我假设迭代每一个都是一个开始,但在那之后我被难住了。

一个丑陋的解决方案:

int number = 0;
string newList = "";
foreach (string item in list.Split(new char[] {','}))
{
if (number > 0)
{
newList = newList + "," + "'" + item + "'";
}
else
{
newList = "'" + item + "'";
}
number++;
}

最佳答案

string s = "A,B,C";
string replaced = "'"+s.Replace(",", "','")+"'";

感谢您的评论,我错过了外部报价。

当然..如果源是一个空字符串,你是否想要在它周围加上额外的引号?如果输入是一堆空格怎么办......?我的意思是,要提供 100% 完整的解决方案,我可能会要求提供单元测试列表,但我希望我的直觉能回答您的核心问题。

更新:还建议了基于 LINQ 的替代方案(具有使用 String.Format 的额外好处,因此不必担心前导/尾随引号):

string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());

关于c# - 在 C# : Add Quotes around string in a comma delimited list of strings 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/254009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com