【问题标题】:How to transform a comma-separated string to line-break-separated string?如何将逗号分隔的字符串转换为换行符分隔的字符串?
【发布时间】:2013-04-25 06:43:08
【问题描述】:

我有一个逗号分隔的字符串。如何将其转换为换行符分隔格式。我的字符串如下所示:

red,yellow,green,orange,pink,black,white

并且需要这样格式化:

red
yellow
green
orange
pink
black
white

这是我的代码:

public static string getcolours()
{
    List<string> colours = new List<string>();
    DBClass db = new DBClass();
    DataTable allcolours = new DataTable();
    allcolours = db.GetTableSP("kt_getcolors");
    for (int i = 0; i < allcolours.Rows.Count; i++)
    {
        string s = allcolours.Rows[i].ItemArray[0].ToString();
        string missingpath = "images/color/" + s + ".jpg";
        if (!FileExists(missingpath))
        {
            colours.Add(s);

        }
    }
    string res = string.Join(", ", colours);

    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"F:\test.txt", true))
    {

        file.WriteLine(res);
    }
    return res;
}

【问题讨论】:

    标签: c# string data-transform


    【解决方案1】:
    res = res.Replace(',','\n');
    

    这应该可行。

    【讨论】:

      【解决方案2】:

      你可以试试:

      string colours = "red,yellow,green,orange,pink,black,white";
      string res = string.Join(Environment.NewLine, colours.Split(','));
      

      或者更简单的版本是:

      string res2 = colours.Replace(",", Environment.NewLine);
      

      【讨论】:

        【解决方案3】:

        不要字符串连接,只需写下颜色,然后在 \n 上加入下一个返回

        public static string getcolours()
        {
            List<string> colours = new List<string>();
            DBClass db = new DBClass();
            DataTable allcolours = new DataTable();
            allcolours = db.GetTableSP("kt_getcolors");
            for (int i = 0; i < allcolours.Rows.Count; i++)
            {
                string s = allcolours.Rows[i].ItemArray[0].ToString();
                string missingpath = "images/color/" + s + ".jpg";
                if (!FileExists(missingpath))
                {
                    colours.Add(s);
                }
            }
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"F:\test.txt", true))
            {
                foreach(string color in colours)
                {
                    file.WriteLine(color);
                }
            }
            return string.Join("\n", colours);;
        } 
        

        【讨论】:

          【解决方案4】:
          var s = "red,yellow,green,orange,pink,black,white";
          var r = string.Join(Environment.NewLine, s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); 
          

          【讨论】:

            猜你喜欢
            • 2019-11-18
            • 1970-01-01
            • 2018-07-19
            • 1970-01-01
            • 2018-08-16
            • 2013-09-30
            • 1970-01-01
            • 2020-11-27
            • 1970-01-01
            相关资源
            最近更新 更多