我有一个逗号分隔的字符串。如何将其转换为换行符格式。我的字符串就像是
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;
}
有人知道如何格式化吗?
答案 0 :(得分:7)
res = res.Replace(',','\n');
这应该有用。
答案 1 :(得分:3)
你可以尝试:
string colours = "red,yellow,green,orange,pink,black,white";
string res = string.Join(Environment.NewLine, colours.Split(','));
或者更简单的版本是:
string res2 = colours.Replace(",", Environment.NewLine);
答案 2 :(得分: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);;
}
答案 3 :(得分:0)
var s = "red,yellow,green,orange,pink,black,white";
var r = string.Join(Environment.NewLine, s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));