2

I have a comma-separated string. How can I convert it into line-break-separated format. My string looks like this:

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

And needs to be formatted to in this way:

red
yellow
green
orange
pink
black
white

Here is my code:

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;
}
leonheess
  • 5,825
  • 6
  • 42
  • 67
Arun
  • 1,332
  • 9
  • 27
  • 55

4 Answers4

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

This should work.

TRMI
  • 143
  • 5
4

you can try:

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

Or much simpler version would be:

string res2 = colours.Replace(",", Environment.NewLine);
Habib
  • 205,061
  • 27
  • 376
  • 407
1

Don't string join, just writeline the colors and next return with join on \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);;
} 
Ruben-J
  • 2,625
  • 11
  • 32
0
var s = "red,yellow,green,orange,pink,black,white";
var r = string.Join(Environment.NewLine, s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); 
jwaliszko
  • 16,235
  • 19
  • 88
  • 151