2

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

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;
}
4

4 回答 4

8
res = res.Replace(',','\n');

这应该有效。

于 2013-04-25T06:47:13.740 回答
4

你可以试试:

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

或者更简单的版本是:

string res2 = colours.Replace(",", Environment.NewLine);
于 2013-04-25T06:45:32.743 回答
1

不要字符串连接,只需写下颜色,然后在 \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);;
} 
于 2013-04-25T06:46:36.793 回答
0
var s = "red,yellow,green,orange,pink,black,white";
var r = string.Join(Environment.NewLine, s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); 
于 2013-04-25T06:48:27.927 回答