更新时间:2022-10-23 12:27:13
字符串s =A,B,C;
字符串替换='+ s.Replace(,,,)+';
感谢您的意见,我已经错过了外部报价。
当然..如果来源是一个空字符串,你会希望它周围多余的引号或不?而如果输入的是一堆空格...的?我的意思是,给予100%的完整的解决方案,我可能会问的单元测试列表,但我希望我的直觉回答了你的核心问题。
的更新的:基于LINQ的替代也被建议(使用的String.Format,因此没有额外的好处不用担心前/后引号):
字符串列表=弗雷德,山姆,迈克,莎拉
串newList =的string.join(,,list.Split(,)选择(X =方式>。的String.Format({0},x)的)了ToList()) ;
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++;
}
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.
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):
string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());