In C#: Add Quotes around string in a comma delimited list of strings

后端 未结 16 1811
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 08:18

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 li         


        
16条回答
  •  猫巷女王i
    2021-01-30 08:54

    My "less sophisticated" approach ... I suppose it's always good practice to use a StringBuilder because the list can be very large.

    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);
    

提交回复
热议问题