如何将逗号分隔的字符串转换为换行分隔的字符串
本文关键字:字符串 分隔 转换 换行 | 更新日期: 2023-09-27 18:10:44
我有一个逗号分隔的字符串。如何将其转换为换行分隔格式。我的字符串如下:
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;
}
res = res.Replace(',',''n');
这应该行得通。
您可以尝试:
string colours = "red,yellow,green,orange,pink,black,white";
string res = string.Join(Environment.NewLine, colours.Split(','));
或者更简单的版本是:
string res2 = colours.Replace(",", Environment.NewLine);
不要使用字符串join,只需在上写下颜色和下一个join返回
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);;
}
var s = "red,yellow,green,orange,pink,black,white";
var r = string.Join(Environment.NewLine, s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));