本文介绍了在C#中:添加引号字符串中的一个逗号分隔的字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有一个简单的答案,但我不能有足够的咖啡弄明白我自己的:



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

 字符串列表=弗雷德,山姆,迈克,莎拉 



该如何获得每个元素和它周围添加引号,并坚持它放回在这样的字符串:

 字符串newList ='弗雷德','萨姆','迈克','莎拉'; 



我假设在每一个迭代是一个开始,但我得到了后难住了。



一个解决方案,它是丑陋的:

  INT数= 0; 
串newList =;
的foreach(在list.Split(字符串项新的char [] {','}))
{
如果(数大于0)
{
newList = newList +,+'+项目+';
}
,否则
{
newList ='+项目+';
}
号++;
}


解决方案

 字符串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());

这篇关于在C#中:添加引号字符串中的一个逗号分隔的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:34